在构建 sql 查询时,它看起来annotate()
没有考虑defer()
(或)。only()
这是一个错误还是出于某种原因这样构建的?
模型:
class Item(models.Model):
a_number = models.PositiveIntegerField()
a_string = models.CharField(max_length=100)
a_date = models.DateField()
查询集:
Item.objects.defer(
'a_number',
'a_date'
).filter(
a_date__lte=datetime.date.today()
).annotate(
number_sum=Sum('a_number')
).order_by("-number_sum")
询问:
SELECT "app_item"."a_string", SUM("app_item"."a_number") AS "number_sum"
FROM "app_item"
WHERE "app_item"."a_date" <= 2012-10-03
GROUP BY "app_item"."id", "app_item"."a_number", "app_item"."a_date", "app_item"."a_string" ORDER BY "number_sum" DESC
我期待:
SELECT "app_item"."a_string", SUM("app_item"."a_number") AS "number_sum"
FROM "app_item"
WHERE "app_item"."a_date" <= 2012-10-03
GROUP BY "app_item"."id", "app_item"."a_string" ORDER BY "number_sum" DESC
我知道我可以使用values()
,但我想要模型实例。
也许有一种简单的方法可以删除 group by 列,因为我仍然想删除 "app_item"."id" fom group by?
我现在将使用 raw 但如果有一个跨数据库解决方案会很好。