首页 > 解决方案 > 如何将 Django 模型计算属性用于 Django 管理器模型?

问题描述

我试图将我的 django 模型计算属性用于自定义管理器以实现自定义结果。但是 django 只允许在管理器中使用普通属性。

我已经尝试将 @property 添加到我的计算属性中,但没有工作。

这是我的代码:

class Produto(models.Model):
    nome = models.CharField(max_length=100)
    fabricante = models.ForeignKey('Fabricante', on_delete=models.PROTECT)
    frete_ipi = models.DecimalField(decimal_places=2, max_digits=10)
    price = models.DecimalField(decimal_places=2, max_digits=10)
    cost_price = models.DecimalField(decimal_places=2, max_digits=10)

    @property
    def real_cost_price(self):
        p = (self.cost_price * self.frete_ipi) + self.cost_price
        return round(p, 2)

而且我正在尝试将“real_cost_price”用于我的经理并且无法正常工作。

class EstoqueCentroManager(models.Manager):
    def total_venda(self):
        total = self.all().aggregate(valor=Sum(F('quantidade') * F('produto__real_cost_price'), output_field=FloatField()))
        return total

我如何将这个计算属性“real_cost_price”用于我的经理?还是有另一种解决方法来实现这种结果?

谢谢!

标签: pythondjango

解决方案


推荐阅读