A cleaner version of what you have would be:
def last_price(self):
latest_price = self.price_set.latest('date')
return latest_price.value if latest_price else None
But this still involves queries for each item.
You if you want to avoid this I would suggest adding a latest_price
column to Product
. Then you could set up a post_save
signal for Price
that then updates the related Product
latest_price
(This could be a ForiegnKey or the value itself.)
Update
Here is a receiver that would update the products latest price value when you save a Price
. Obviously this assumes that you are saving Price
models in chronological order so the lastest one saved is the latest_value
@receiver(post_save, sender=Price)
def update_product_latest_value(sender, instance, created, **kwargs):
if created:
instance.product.latest_value = instance.value
instance.product.save()