Django多注释返回错误结果

2024-09-24 12:27:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在django查询集中创建注释。注释是基于条件的反向外键计数。我遇到的问题是,当我用一个条件计算一个反向外键时,我得到了正确的数据,但是当我做两个注释时,每个反向外键一个注释。你知道吗

以下是一个反向外键的带有计数注释的查询集:

ExamResponse.objects.filter(
        course_class__course=course,
        exam__exam_type=Exam.PRACTICE,
        user__is_demo=False,
        ended__isnull=False,
        id=125752
    ).order_by(
        'user_id',
        'started'
    ).annotate(
        total_ecq_count=Sum(
            Case(
                When(
                    choice_questions__response_time__gte=ENGAGEMENT_THRESHOLD,
                    choice_questions__id__isnull=False,
                    then=1
                ),
                default=0,
                output_field=IntegerField()
            ), 
            distinct=True
        ),
    ).values('total_ecq_count')

结果(正确结果):

<QuerySet [{'total_ecq_count': 1}]>

带有两个计数注释的查询

ExamResponse.objects.filter(
        course_class__course=course,
        exam__exam_type=Exam.PRACTICE,
        user__is_demo=False,
        ended__isnull=False,
        id=125752
    ).order_by(
        'user_id',
        'started'
    ).annotate(
        total_ecq_count=Sum(
            Case(
                When(
                    choice_questions__response_time__gte=ENGAGEMENT_THRESHOLD,
                    choice_questions__id__isnull=False,
                    then=1
                ),
                default=0,
                output_field=IntegerField()
            ), 
            distinct=True
        ),
        total_etq_count=Sum(
            Case(
                When(
                    text_questions__response_time__gte=ENGAGEMENT_THRESHOLD,
                    text_questions__id__isnull=False,
                    then=1
                ),
                default=0,
                output_field=IntegerField()
            ), 
            distinct=True
        ),
    ).values('total_ecq_count', 'total_etq_count')

结果:(ecq总数由1增加到3!!!)你知道吗

<QuerySet [{'total_ecq_count': 3, 'total_etq_count': 4}]>


Tags: idfalsecount外键total计数questionssum