I have three models, simplified for the example:
class Customer(models.Model):
email = models.CharField(max_length=128)
class Order(models.Model):
custo
You could try using a property in the LineItem
model:
class Lineitem(models.Model):
order = models.ForeignKey(Order)
quantity = models.IntegerField(blank=True)
price = models.DecimalField(max_digits=6, decimal_places=2)
def _get_total(self):
return quantity * price
total = property(_get_total)
Then I think you can annotate with the total amount spent using
Customer.objects.filter(something).annotate(total_spent=Sum('order__lineitem__total'))
I don't know how the efficiency of this method relates to others, but it is more Pythonic/Django-y than the alternative, which is to write the entire SQL query by hand as in
Customer.objects.raw("SELECT ... from where ...")