[Answered ]-Getting total price for a ManyToManyField in Django

1đź‘Ť

âś…

Moved from above.

If I understand correctly, you could just retrieve the sum from the object itself. So if you have an Order called “order” where the products are already assigned (during the saving process, you should be able to something like:

order.total_price = order.number_of_products.all().aggregate(Sum('price_for_each_item')). 

Let me know if this answers your question and I’ll move it to an answer.

Glad I could help. Not to be a nazi here, please give more thought to your model field names in the future, they are seriously confusing.

Edit re your comment:

I’m not sure but I think overriding your model’s save method would be the way to go to get it to work in admin:

def save(self):
        super(Person, self).save()
        self.total_price = self.number_of_products.all().aggregate(Sum('price_for_each_item')). 
        self.save(commit=True)

Haven’t tested this at all though. Have a look at this:
http://ifacethoughts.net/2009/07/14/calculated-fields-in-django/
If it works, could you accept the answer.

👤MikkoP

1đź‘Ť

No need to add the dollar_amount field, that is duplicate information. Instead make it a property, this is how you get the total price:

from django.db.models import Sum

p = PurchaseOrder.objects.filter(...)
p.annotate(Sum("products__price_for_each_item")
👤Kimvais

Leave a comment