views:

188

answers:

1

I have three models, simplified for the example:

class Customer(models.Model):
    email = models.CharField(max_length=128)

class Order(models.Model):
    customer = models.ForeignKey(Customer)
    order_status = models.CharField(blank=True, max_length=256)

class Lineitem(models.Model):
    order = models.ForeignKey(Order)
    quantity = models.IntegerField(blank=True)
    price = models.DecimalField(max_digits=6, decimal_places=2)

I want to query the customers (possibly with a filter) and annotate the total they have spent (that is, the sum over (price * quantity)

I have tried:
Customer.objects.filter(something).annotate(total_spent=Sum(F('order__lineitem__quantity') * F('order__lineitem__price')))

It would appear that Sum() cannot be used with F() expressions. Is there another way to do this?

A: 

Have you looked at using the .extra() method?

See the Django QuerySet API.

Grant
I have. It works, but I'm trying to avoid it for two reasons: First, it uses a per-row subquery instead of a join, which may scale badly for some database backends. Second, it doesn't work with filter() on the extra field, so it can't be combined procedurally with other Q objects
Sam