0

I have a query that looks like the following:

filter = Q(filter stuff)
q = MyModel.objects.filter(filter).order_by().values('c1', 
                                                     'c2', 
                                                     'c3').annotate(Sum('c2'), Sum('c3'))

Now when I do this, the output essentially has all the unique triples of c1, c2, and c3. Which I don't want. I want it find all the unique values of c1, and add up the corresponding values of c2 and c3.

I was able to fix this by changing the query to the following

q = MyModel.objects.filter(filter).order_by().values('c1', 
                                                    ).annotate(Sum('c2'), Sum('c3'))

Which is great and gives me the desired output...but what I don't understand is why...

Shouldn't values specify the columns that I want, not restrict the output to the unique pairings of those outputs? Any help would be appreciated

1 Answer 1

2

Now when I do this, the output essentially has all the unique triples of c1, c2, and c3.

values() is going to return an object's specific set of c1, c2 and c3 as a dictionary. Yes, this is expected behavior.

Moving on:

I want it find all the unique values of c1, and add up the corresponding values of c2 and c3.

Alrighty than: first get the c1 value for each object in the queryset with value and then use annotate to add the sums of 'c2' and 'c3'. You thit a good job doing that.

So yes, this is correct:

q = MyModel.objects.filter(filter).order_by().values('c1', 
                                                    ).annotate(Sum('c2'), Sum('c3'))

Shouldn't values specify the columns that I want, not restrict the output to the unique pairings of those outputs?

In this case the column you want is c1, you don't really want the columns c2 and c3, you just want to aggregate sum them.

values() is going to restrict the output to the unique pairings because that is a row in the database. There is no magic in values(), it just turns a model instance into a dictionary.

Hope it helps.

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

Comments

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.