Annotate a sum of two fields multiplied

后端 未结 6 851
闹比i
闹比i 2021-01-30 13:28

I have three models, simplified for the example:

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

class Order(models.Model):
    custo         


        
6条回答
  •  梦毁少年i
    2021-01-30 13:56

    I just ran into this and I don't think that annotate and will work with a property, see Django - Can you use property as the field in an aggregation function?

    Here is what I did.

    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)
        @property
        def total(self):
            return self.quantity * self.price
    

    Then use sum and a list comprehension:

    sum([li.total for li in  LineItem.objects.filter(order__customer=some_customer).filter(somefilter)])
    

提交回复
热议问题