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

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

问题描述

在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.

但是,这code结果只能过滤的对象; 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 ...

然后取出注解和你的循环应该工作原样。这将意味着有更多疑问,但他们会更简单,你可以随时缓存它们。

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天全站免登陆