【问题标题】:Django annotate() and count() conditional from 0 to nullDjango annotate() 和 count() 条件从 0 到 null
【发布时间】:2020-08-10 13:46:07
【问题描述】:

我是 django 和 django-rest-framework 的新手,我想知道是否可以将条件 if else 放在 annotate(total_sessions=Count()) where if Count() = 0 then total_sessions="null"?我有一个项目,如果总会话数等于 0,则输出必须为空。

我虽然在 total_sessions 上使用 SerializerMethodField() 来获取计数,但这会导致多个 SQL 查询导致 API 响应缓慢,这就是它不可能的原因。

下面是 serializers.py 和 views.py 的示例代码(这只是一个示例代码,因为我的真实代码有多个查询集)。

序列化器.py

class ClassStatisticsSerializer(ModelBaseSerializer):
    total_sessions = serializers.IntegerField()

    class Meta:
        model = Class
        fields = (
           'id',
           'batch',
           'type,
           'total_sessions'
        )

views.py

from django.db.models import Count, Q
class ClassStatisticsList(APIView):
    condition = {}
    if date:
        condition = {'classactivity__date':date}

    queryset = Class.objects.all().annotate(
        total_sessions=Count(
            'classactivity',
            filter=Q(**condition),
            distinct=True
        )
    )

【问题讨论】:

    标签: python django django-models django-rest-framework django-serializer


    【解决方案1】:

    您正在寻找在 Django 网站上有详细记录的 Conditional Expressions

    下面的sn-p我没试过(只是对你的代码进行了扩充),只是给你一个起点:

    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'
            )
        )
    

    【讨论】:

    • 非常感谢。我已经在阅读条件表达式,但我以错误的方式实现它。您的实施解决了它。再次,非常感谢。
    猜你喜欢
    • 2021-11-28
    • 2016-10-31
    • 2019-01-01
    • 2017-10-02
    • 2016-05-11
    • 2021-04-24
    • 2012-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多