I've got an Invoice
model, and I want to keep the total
up to date. So I've added a property like this
@property
def item_total(self):
if not hasattr(self, 'item_total_cache'):
self.item_total_cache = self.items.aggregate(t=Sum('amount'))['t']
return self.item_total_cache
Because item_total
might get called a few times during one page request and I don't want to hit the DB every time. Is this a good way to do it? Will my Invoice
object exist beyond one page request and thus the item_total
might actually get stale?
Ideally, I'd like to compute the item_total
at the same time the invoices are requested... I know I can do this manually, but the Django admin site, for instance, doesn't know it's going to need the sum. Is there someway I can "inject" this extra tidbit of information so that all Invoice.objects.all/filter/get()
requests run the aggregate at the same time?