我有这些模型和经理:
class ItemManager(models.Manager):
use_for_related_fields = True
def get_queryset(self):
qs = super().get_queryset()
return qs.annotate(total_price=ExpressionWrapper(
F('gross_price') * F('qty'), output_field=models.DecimalField())
)
class OrderManager(models.Manager):
use_for_related_fields = True
def get_queryset(self):
qs = super().get_queryset()
return qs.annotate(total_price=Sum(items__total_price)) # this doesnt work
class Order(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length='50')
class Item(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
price = models.DecimalField(max_digits=14, decimal_places=2)
qty = models.IntegerField()
order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE)
objects = ItemManager()
我想获得订单的总价,如下所示:
for sale in Order.objects.all():
print(sale.total_price)
错误:
django.core.exceptions.FieldError: Unsupported lookup 'total_price' for UUIDField or join on the field not permitted.
我可以得到total_price
每个项目,我想用它total_price
来获得所有项目的总和。我需要这种方式,因为我将在具有多个订单作为子元素的模型中使用该销售总价。