问题
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:
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.
来源:https://stackoverflow.com/questions/10376699/annotate-then-filter-then-annotate