3👍
No reason to save it in the database, just make it a method or property of the Quote
object:
class Quote(models.Model):
...
def quotee_total(self):
return self.quotee_products.aggregate(total=models.Sum('product_price'))['total']
If need be, you can cache the value and fill the cache on the initial query:
class Quote(models.Model):
...
def quotee_total(self):
if not hasattr(self, '_quotee_total'):
self._quotee_total = self.quotee_products.aggregate(total=models.Sum('product_price'))['total']
return self._quotee_total
quotes = Quote.objects.annotate(_quotee_total=models.Sum('quotee_products__product_price'))
You can of course save that value in the database, but there’s little reason. If you’re worried about performance, that is better handled with caching than with saving the value to the database.
👤knbk
1👍
I would not calculate the total in a view. This makes more sense as a method.
class Quote(models.Model):
def calculate_quotee_total(self):
return sum(product.product_price for product in self.quotee_products.all())
def __save__(self):
self.quotee_total = self.calculate_quotee_total()
super(Quote, self).save()
Quote.quotee_total could also be calculated as needed, instead of saving it in the db.
class Quote(models.Model):
@property
def quotee_total(self):
return sum(product.product_price for product in self.quotee_products.all())
- [Django]-Save 404 Error's URL in Django in models
- [Django]-Django start new project error
- [Django]-Empty ChoiceField selection in Django forms
- [Django]-IPN delivery failed. HTTP error code 403: Forbidden
Source:stackexchange.com