Reputation: 1
I have these three models : MenuItem
, Subs
and Pizzas
Both Subs and Pizzas have a foreign relation on MenuItem, for example :
menuItem = models.ForeignKey('MenuItem', related_name='pizza', on_delete=models.CASCADE)
Moreover, both Subs and Pizzas have a @property price()
property. I would like to access this price property from the MenuItem, in order to be able to compute the price of an order.
What would be the best way to implement this ?
I have thought about defining a price() property in MenuItem, but then how do I access the reverse relation in order to retrieve the price, considering there may be multiple reverse relations ? Do I need to check every possible reverse relations, to find one that is not Null, and then access the price ?
Thank you
Upvotes: 0
Views: 39
Reputation: 52028
You can try like this:
menu = MenuItem.objects.first()
pizza_prices = 0
for pizza in menu.pizza.all():
pizza_prices += pizza.price
sub_prices = 0
for sub in menu.sub.all():
sub_prices += sub.price
More information can be found in documenation
.
Upvotes: 1