R
R
raiboon2014-12-03 19:27:28
PostgreSQL
raiboon, 2014-12-03 19:27:28

How to sum multiple fields in Django when grouping?

There is a table like this:

id  |   started |   finished
1   |   2       |   1       
2   |   2       |   1       
1   |   4       |   3

How to group by id and get sums?
So that we get objects like {id:1, started:6, finished:4}, {id:2,started:2,finished:1}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2014-12-04
@raiboon

I think you need this: djbook.ru/rel1.6/topics/db/aggregation.html#genera...
If you have a model

class Habr(models.Model):
    idn = models.Integer()
    started = models.Integer()
    finished = models.Integer()

then the desired result can be obtained as follows:
input:  from app.models import Habr
input:  habr = Habr.objects.all()
input:  from django.db.models import Sum
input:  habr.values('idn').annotate(s1=Sum('started'),s2=Sum('finished'))

output: [{'idn': 1, 's2': 4, 's1': 6}, {'idn': 2, 's2': 1, 's1': 2}]

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question