【发布时间】:2016-08-11 00:55:43
【问题描述】:
我有一个模型 test 有两个 m2m 字段:foo 和 bar。
我正在尝试对这些相关字段的条件计数进行注释,即对满足特定条件的相关对象进行计数。在查询集之外检索此信息不是一种选择,因为我需要使用带注释的字段来对结果进行排序。
我尝试了以下方法:
1.使用预取对象
from django.db.models import Prefetch, Count
prefetch_foo = Prefetch('foo_set', queryset=foo.objects.filter(<some condition>))
prefetch_bar = Prefetch('bar_set', queryset=bar.objects.filter(<some condition>))
result = test.objects.prefetch_related(prefetch_foo, prefetch_bar).annotate(n_foo=Count('foo'), n_bar=Count('bar'))
这不起作用,因为prefetch_related 在annotate 之后应用。
2。使用条件表达式
from django.db.models import Sum, Case, When
from django.db.models.fields import IntegerField
foo_sum = Sum(Case(When(foo__<some condition>, then=1), default=0,
output_field=IntegerField())))
bar_sum = Sum(Case(When(bar__<some condition>, then=1), default=0,
output_field=IntegerField())))
result = test.objects.annotate(n_foo=foo_sum, n_bar=bar_sum)
这不起作用,因为多个 Sum 注释上的这个错误:https://code.djangoproject.com/ticket/10060
3.使用 RawSQL
sql = "SELECT SUM(CASE WHEN foo.<condition> "
"THEN 1 ELSE 0 END) FROM app_test "
"LEFT OUTER JOIN app_foo "
"ON (app_test.id = foo.test_id) "
"GROUP BY test.id"
result = test.objects.annotate(n_foo=RawSQL(sql, []))
# Same method for bar
我被困在这里,因为这会检索所有行的 SUM,但我找不到添加类似 "WHERE test.id = <ID of the object the annotation corresponds to>" 的方法。
有没有办法从自定义 SQL 中获取正确的单行?还是其他解决方法?
【问题讨论】:
标签: sql django orm annotations