Django聚合:使用ForienKey对两个字段进行乘法求和

问题描述

我有以下两个模型

class Product(models.Model):
     title = models.CharField(max_length=128)
     slug = models.SlugField()
     price = models.DecimalField(default=0.0,decimal_places=2,max_digits=15,validators=[MinValueValidator(Decimal('0.00'))])

     def __str__(self):
         return str(self.title)

class OrderItem(models.Model):
    product = models.ForeignKey(Product,on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)

    def __str__(self):
        return f"{self.quantity} of {self.product.title}"

    def subtotal(self):
         return self.quantity * self.product.price

我希望使用汇总来汇总所有小计,但是

total1 = OrderItem.objects.all().aggregate(total=Sum(F('product.price') * F('quantity')))['total']

返回Cannot resolve keyword 'product.price' into field. Choices are: id,order,product,product_id,quantity

total2 = OrderItem.objects.all().aggregate(total=Sum(F('subtotal') * F('quantity')))['total']

返回Cannot resolve keyword 'subtotal' into field. Choices are: id,quantity,错误

解决方法

经过研究,我发现

from django.db.models import Sum,F


total =  OrderItem.objects.all().aggregate(total=Sum(F('product__price') * F('quantity')))['total']

会做