第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Django annotate() 和 count() 條件從 0 到 null

Django annotate() 和 count() 條件從 0 到 null

慕村9548890 2023-05-09 15:11:13
我是 django 和 django-rest-framework 的新手,我想知道是否可以在 annotate(total_sessions=Count()) where if Count() = 0 then total_sessions="null" 上放置條件 if else?我有一個項目,如果總會話數(shù)等于 0,則輸出必須為空。我雖然在 total_sessions 上使用 SerializerMethodField() 來獲取計數(shù),但這會導致多個 SQL 查詢導致 API 響應緩慢,這就是它不可能的原因。下面的示例代碼用于 serializers.py 和 views.py(這只是一個示例代碼,因為我的真實代碼有多個查詢集)。serializers.pyclass ClassStatisticsSerializer(ModelBaseSerializer):    total_sessions = serializers.IntegerField()    class Meta:        model = Class        fields = (           'id',           'batch',           'type,           'total_sessions'        )views.pyfrom django.db.models import Count, Qclass ClassStatisticsList(APIView):    condition = {}    if date:        condition = {'classactivity__date':date}    queryset = Class.objects.all().annotate(        total_sessions=Count(            'classactivity',            filter=Q(**condition),            distinct=True        )    )
查看完整描述

1 回答

?
catspeake

TA貢獻1111條經(jīng)驗 獲得超0個贊

您正在尋找在 Django 站點上有詳細記錄的條件表達式。

我沒有嘗試過以下代碼片段(這只是您的代碼增強),它只是給您一個起點:

queryset = Class.objects.all()

? ? .annotate(

? ? ? ? total_session_cnt=Count(

? ? ? ? ? ? 'classactivity',

? ? ? ? ? ? filter=Q(**condition),

? ? ? ? ? ? distinct=True

? ? ? ? )

? ? )

? ? .annotate(

? ? ? ? total_sessions=Case(

? ? ? ? ? ? When(total_session_count=0, then=Value(None, output_field=IntegerField())),

? ? ? ? ? ? default='total_session_count'

? ? ? ? )

? ? )


查看完整回答
反對 回復 2023-05-09
  • 1 回答
  • 0 關注
  • 231 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號