0

The code:

now = datetime.now()
year_ago = now - timedelta(days=365)
category_list = Category.objects.annotate(suma = Sum('operation__value')) \
                                .filter(operation__date__gte = year_ago) \
                                .annotate(podsuma = Sum('operation__value'))

The idea: get sum of each category and sum of one year back.

But this code result only filtered objects; suma is equal to podsuma.

1 Answer 1

2

A queryset only produces one query, so all annotations are calculated over the same filtered data set. You'll need to do two queries.

Update:

Do something like this:

In models.py

class Category(models.Model):
    ...
    def suma(self):
        return ...
    def podsuma(self):
        return ...

Then remove the annotations and your for loop should work as is. It'll mean a lot more queries, but they'll be simpler, and you can always cache them.

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

3 Comments

Ok - so how to solve the problem? I need it in one queryset - in template there is {for loop}
I'd write methods on the Category class - I've updated the answer with an example.
stackoverflow.com/questions/10380392/… there is the full solution - but thanks for explaining the main problem -

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.