假设我有以下模型结构:
class SomeModel(Model):
base_price = DecimalField(....)
commision = DecimalField(....)
为了数据的一致性,我不想在我的数据库中存储total_price
,而是希望将其计算为base_price + commision
,例如
SomeModel.Objects.all().xxxxxx(total_price=base_price + commision)
所以我的数据库(Postgresql 9.1)将计算并返回它而不将其记录在数据库中并且返回查询集中的每条记录将包含 total_price
即 base_price
和commision
该记录。如果我可以在计算字段上使用 filter
也会很棒。
我该怎么做?
我想要类似于以下 SQL 的东西:
select ("base_price" + "commision") as total_price, base_price, commision from some_table;
total_price | base_price | commision
-------------------------------------
15.0 | 14.0 | 1.0
22.0 | 20.0 | 2.0
请您参考如下方法:
1.您可以使用extra()
查询集方法:
SomeModel.objects.extra(select={'total_price': 'base_price + commission'})
上面将为QuerySet 中的每个项目添加一个total_price
属性。但是,您将不能对其进行过滤——您将得到一个FieldError: Cannot resolve keyword 'total_price' into field
。
2. 有一个undocumented way使用 annotate()
添加一个可以过滤的字段。在你的情况下它会是这样的:
from django.db.models import Max
# with this method the total_price can be filtered on
SomeModel.objects.annotate(
total_price=Max('base_price', field='base_price + commission')
).filter(total_price__lt=20)