python - Django 多注解返回错误结果
问题描述
我正在尝试在 django 查询集中创建注释。注释是基于条件的反向外键计数。我遇到的问题是,当我使用条件对一个反向外键进行计数时,我得到了正确的数据,但是当我进行两个注释时,每个反向外键一个。
这是一个反向外键的带有 Count 注释的查询集:
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}]>
带有两个 Count 注释的查询
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')
结果:(total_ecq_count 从 1 变为 3!!!)
<QuerySet [{'total_ecq_count': 3, 'total_etq_count': 4}]>
解决方案
我刚刚发现这篇文章,显然,这是一个已知错误,两个不同外键的两个注释会创建重复计数。https://code.djangoproject.com/ticket/25861
推荐阅读
- c# - 在 C# 中正确使用 Try Catch 进行 SQL 连接
- java - java存储在同一个对象中的两个不同的类加上在网格中显示
- html - 向 innerHTML 添加样式
- java - 在java中通过println打印字符序列时出错
- iis - 在 ASP.Net Core 2 中刷新 Window 身份验证用户的用户声明和角色
- bash - Is my bash script vulnerable to command injection?
- command-line - 如何从终端编辑 py 文件?
- python - pandas won't import despite trying many versions of python
- javascript - 图像无法正确加载
- python - 使用下拉列表过滤带有 django-filters 的 django-tables2 表