Skip to content
Advertisement

Django, how to write SQL or ORM to sum something?

I want to count something like this:

input list:

  • AAA female 1
  • AAA female 2
  • BBB male 2
  • BBB male 1
  • AAA male 1

output list:

  • AAA male 1
  • AAA female 3
  • BBB male 3

Sorry, my english is not good, thanks for everyone who help me.

Advertisement

Answer

Don’t know your exact model struture, but the queries you need to run should be something like the following:

Assuming your model name is “YourModel”, field containing “AAA” or “BBB” is “field_1”, field containing “male” of “female” is “field_2”, and the field containing numeric value is “field_3”

from django.db.models import Sum
YourModel.objects.filter(field_1='AAA', field_2='male').aggregate(sum=Sum('field_3')).get('sum')  # AAA male 1
YourModel.objects.filter(field_1='AAA', field_2='female').aggregate(sum=Sum('field_3')).get('sum')  # AAA female 3
YourModel.objects.filter(field_1='BBB', field_2='male').aggregate(sum=Sum('field_3')).get('sum')  # BBB male 3

I saw from your comment on the question that you want to group on name and gender, then sum their counts. You can do that with annotations as follows:

from django.db.models import Sum
YourModel.objects.values('name', 'gender').annotate(sum=Sum('count'))

Here you group by name and gender with the part values(‘name’, ‘gender’) and annotate each name – gender pair row with the sum of counts.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement