annotate then filter then annotate

匆匆过客 提交于 2019-12-25 00:16:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!