I have a method in the model that saves the final price in the cart, it looks like this:
class Cart(models.Model):
"""Cart"""
owner = models.OneToOneField('Customer', on_delete=models.CASCADE)
meals = models.ManyToManyField(CartMeal, related_name='related_cart', blank=True)
total_products = models.PositiveIntegerField(default=0)
final_price = models.DecimalField(max_digits=9, decimal_places=2, default=0)
in_orders = models.BooleanField(default=False)
for_anonymous_user = models.BooleanField(default=False)
def save(self, *args, **kwargs):
if self.id:
self.total_products = self.meals.count()
self.final_price = sum([cmeals.final_price for cmeals in self.meals.all()])
super().save(*args, **kwargs)
I was told that I can make this line self.final_price = sum([cmeals.final_price for cmeals in self.meals.all()])
with a single query using aggregate.
How can I do this and where? In the model or do I need to do this in the view? Thanks.
CodePudding user response:
Cart.objects.aggregate(
final_price=Sum(F('meals__final_price'),
output_field=IntegerField()
)
# returns ->
{'final_price': 10}
I would suggest not to store it in db, but create a property in model
@property
def final_price(self):
return self.meals.aggregate(
final_price=Sum(F('final_price'),
output_field=IntegerField()
)["final_price"]
It can be accessed same as field:
my_cart.final_price