我是 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'
? ? ? ? )
? ? )
添加回答
舉報
0/150
提交
取消