1

Current Model.objects.all() creates:

 FK Column  Column1  Column2  Column3
  Zone 1        19      23       67
  Zone 2        45      12       76
  Zone 1        23      98       34
  Zone 2        12      56       23

Expected Results:

 FK Column  Column1  Column2  Column3
  Zone 1        42      101       111
  Zone 2        57      68        99

The FKs are automatically combined into a single row.

which query should I use exactly for achieving this?

1
  • What kind of output do you expect? A list of dictionaries? Commented Jul 16, 2018 at 20:46

1 Answer 1

1

You can do this with a .values(..) together with an .annotate(..) and .order_by(..):

Model.objects.values(
    'fk_column'
).annotate(
    sumcol1=Sum('col1'),
    sumcol2=Sum('col2'),
    sumcol3=Sum('col3'),
).order_by('fk_column')

This will result in a QuerySet of dictionaries. Each dictionary contains an 'fk_column', 'sumcol1', 'sumcol2', and 'sumcol3'. These parameters can then be processed further.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi thanks. It solved my problem but what if i need the object name of the foreign key. It is currently returning pk.
@Ohid: then you can fetch it wit extra queries like RelatedModel.objects.get(pk=some_pk), or RelatedModel.objects.get(pk__in=list_of_pks).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.