【发布时间】:2018-10-24 19:05:30
【问题描述】:
我正在尝试从模型中聚合整数列表。整数派生的字段是@property 装饰器字段。装饰器按预期工作,并且在 template.html 内,如果直接传递,则显示没有问题。但是,如果我尝试通过.aggregate() 传递@property 字段,则传递给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。
【问题讨论】:
标签: python django python-3.x django-views