注释然后过滤然后注释 [英] annotate then filter then annotate

查看:30
本文介绍了注释然后过滤然后注释的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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.

但此代码仅导致过滤对象;suma 等于 podsuma.

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

推荐答案

一个查询集只产生一个查询,所以所有的注释都是在同一个过滤数据集上计算的.您需要进行两次查询.

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

更新:

做这样的事情:

在models.py中

In models.py

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

然后删除注释,您的 for 循环应该可以正常工作.这将意味着更多的查询,但它们会更简单,而且您可以随时缓存它们.

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.

这篇关于注释然后过滤然后注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆