【发布时间】:2019-04-15 10:37:33
【问题描述】:
在我的 Django 代码中,对于 OrderedArticle 对象,我需要计算 hist_price,它是 2 个字段的乘积:hist_unit_price * quantity。
我做的第一个方法是一个简单的属性:
class OrderedArticle(Model):
@property
def hist_price(self):
return self.hist_unit_price * self.quantity
然后,我意识到当我需要对这些价格进行大量计算时,出于性能原因,我不能使用此属性,而是必须在数据库级别计算 hist_price。这就是为什么我为此编写了一个自定义查询集:
class OrderOperationQuerySet(Queryset):
@staticmethod
def _hist_price(orderable_field): # can be an OrderedArticle or another object here
return ExpressionWrapper(
F(f'{orderable_field}__hist_unit_price') * F(f'{orderable_field}__quantity'),
output_field=DecimalField())
目前,我的代码中同时使用了hist_price 属性和_hist_price 查询集。
问题
这很好用,但我很恼火两次编写相同的业务逻辑。我有一种感觉,我在这里做的不是“正确的方式”。 我认为我应该在代码级别确保无论我使用属性还是查询集,它总是返回相同的结果。 在这种特定情况下,业务逻辑是两个小数之间的简单乘法,所以应该没问题,但我的代码中会有其他情况更复杂。
您发现改进我的代码的方法了吗?谢谢。
【问题讨论】:
标签: python django django-models