Can support django support group on some columns at the same time as the sum on other columns

as request below:

select sum(Ta), sum(Tb) from Table T group by Tc , Td 

Is there a way in django to support this kind of request?

+4
source share
3 answers

It's close:

 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) 

result:

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"

Why GROUP BY values ​​are repeated, I have no idea ...

+5
source

The following worked for me:

 >>> 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" 

Refer to the Django aggregation documentation for reference.

+1
source

Yes, django supports it, its documented here

0
source

Source: https://habr.com/ru/post/1346148/


All Articles