Annotate a sum of two fields multiplied

后端 未结 6 849
闹比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条回答
  •  说谎
    说谎 (楼主)
    2021-01-30 14:11

    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 ...")
    

提交回复
热议问题