.aggregate() 中使用的 Django @property [英] Django @property used in .aggregate()

查看:8
本文介绍了.aggregate() 中使用的 Django @property的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从模型中汇总整数列表.整数派生自的字段是 @property 装饰器字段.装饰器按预期工作,并且在 template.html 内,如果直接传递,则显示没有问题.但是,如果我尝试通过 .aggregate() 传递 @property 字段,则传递到 template 的上下文会抛出一个错误,基本上说 <代码>无法将关键字sum_thing"解析为字段. 后跟不包含任何装饰器字段的模型字段列表.

I'm trying to aggregate a list of integers from a model. The field that the integers are derived from are an @property decorator field. The decorator works as expected and within the template.html, if passed directly, displays without a problem. If however, I try and pass the @property field through .aggregate() the context passed into the template throws an error that basically says Cannot resolve keyword 'sum_thing' into field. followed by a list of model fields that don't include any of the decorator fields.

我的问题是 - 您如何从模型中聚合 (Sum) 派生字段?

My question is - how do you aggregate (Sum) derived fields from the model?

#models.py

class Foo(models.Model):
    a = 10      # a & b are both
    b = 5       # models.IntegerField() items

    @property
    def sum_thing(self):
        return self.a - self.b

#views.py

class Bar(generic.ListView):

    def get_context_data(self, **kwargs):

        qs = Foo.object.all()

        totals = {}

        totals['sumthing'] = qs.aggregate(total=Sum('sum_thing')

        context = {
            'totals': totals
        }

        return context

** 我大大简化了 models.pyviews.py.

** I've greatly simplified the models.py and the views.py.

推荐答案

您不能使用属性进行聚合,因为它不存在于数据库中.但是,您可以在 Django 的 F 表达式的帮助下对查询进行注释,以获取这些字段的实际值.请参阅下面的示例.

You can not aggregate using properties since it does not exist in the db. But, you can annotate your query with the help of Django's F expressions to get the actual value for those fields. See the example below.

from django.db.models import F, Sum

Foo.objects.annotate(sum_a_and_b=F('a') + F('b')).aggregate(total=Sum('sum_a_and_b'))

你也可以做任何数学运算,比如/* + - with F,你也可以这样做

Also you can do any mathematical operation like / * + - with F, also you can do like this

.annotate(answer=F('a') + F('b') * 2)

这篇关于.aggregate() 中使用的 Django @property的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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