就像下面的查询一样:
select sum(T.a), sum(T.b) from Table T group by T.c , T.d
django有什么办法支持这种查询吗?
答案 0 :(得分:5)
这很接近:
class Test(models.Model):
class Meta:
app_label = 'ignore'
db_table = 'T'
a = models.IntegerField()
b = models.IntegerField()
c = models.IntegerField()
d = models.IntegerField()
result = Test.objects.values('c', 'd').annotate(Sum('a'), Sum('b'))
print str(result.query)
结果:
SELECT“T”。“c”,“T”。“d”,SUM(“T”。“a”)AS“a_ sum”,SUM(“T”。“b”)AS “b _sum”FROM“T”GROUP BY“T”。“c”,“T”。“d”,“T”。“c”,“T”。“d”
为什么重复GROUP BY值,我不知道......
答案 1 :(得分:1)
以下对我有用:
>>> from django.db.models import Sum
>>> from myapp.models import T
>>> results = T.objects.values('c', 'd').annotate(Sum('a'), Sum('b'))
>>> print results.query
SELECT "myapp_t"."c", "myapp_t"."d", SUM("myapp_t"."a") AS "a__sum", SUM("myapp_t"."b") AS "b__sum" FROM "myapp_t" GROUP BY "myapp_t"."c", "myapp_t"."d"
答案 2 :(得分:0)
是的,django支持它,它记录在案here