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

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

问题描述

我正在尝试汇总模型中的整数列表。整数派生的字段是 @property 装饰字段。装饰器可以按预期工作,并且在 template.html 内,如果直接传递,则显示不会出现问题。但是,如果尝试通过 .aggregate()传递 @property 字段,则将上下文传递到模板引发错误,基本上说无法将关键字'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.

我的问题是-如何汇总模型中的(求和)派生字段?

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.py views.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'))

此外,您也可以使用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天全站免登陆