In my Django code, for OrderedArticle
objects I need to compute a hist_price
which is the multiplication of 2 fields: hist_unit_price
* quantity
.
The first way I did it was a simple property:
class OrderedArticle(Model):
@property
def hist_price(self):
return self.hist_unit_price * self.quantity
Then, I realised that when I need to make extensive computing of these prices, I can't use this property for performance reason, and instead I must compute hist_price
at a database level. That's why I wrote a custom queryset for this:
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())
Currently, both hist_price
property and _hist_price
queryset are used in my code.
Question
This works well, but I'm annoyed to write the same business logic twice. I have a feeling I'm not doing it "the right way" here. I think I should ensure at a code level, that no matter if I use the property or the queryset, it always returns the same result. In this specific case, the business logic is a simple multiplication between two decimals, so it should be OK, but I'll have other cases in my code where it's way more complex.
Do you see a way to improve my code? Thanks.