.aggregate()中使用的Django @property
我正在尝试从模型中汇总整数列表。整数派生的@property
字段是装饰器字段。装饰器按预期工作,并且在内template.html
,如果直接传递,则显示不会出现问题。但是,如果尝试将@property
字段.aggregate()
传递给template
引发错误的上下文,则该错误基本上会说出一个错误,Cannot
resolve keyword 'sum_thing' into field.
然后显示一系列不包含任何装饰器字段的模型字段。
我的问题是-如何汇总模型中的(求和)派生字段?
#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
。