1

我有这些模型和经理:


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来获得所有项目的总和。我需要这种方式,因为我将在具有多个订单作为子元素的模型中使用该销售总价。

4

1 回答 1

2

如果您查询相关模型,这些相关模型不会“通过”.objects管理器。您可以覆盖._base_manager等。但我强烈建议不要这样做。

您可能最好自己做这项工作OrderManager

class OrderManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self):
        return super().get_queryset().annotate(
            total_price=Sum(F('items__price') * F('items__qty'))
        )
于 2019-09-18T12:38:09.707 回答