TypeError:不支持的操作数类型为*:'PositiveIntegerField'和'int'

问题描述:

您好,我遇到了一个我认为很简单的问题。我有以下类:TypeError:不支持的操作数类型为*:'PositiveIntegerField'和'int'

class Plant(models.Model): 
    nominal_power = models.PositiveIntegerField() 
    module_nominal_power= models.PositiveIntegerField() 

    def calculation_of_components(a, b): 
     return int((a*1000)/b) 

    no_modules=calculation_of_components(nominal_power,module_nominal_power) 

,我得到的错误: TypeError: unsupported operand type(s) for *: 'PositiveIntegerField' and 'int'

我怎样才能解决这个问题?

+0

一种方法是你可以转换'PositiveIntegerField'回'int':'nominal_power = INT(models.PositiveIntegerField())''module_nominal_power = INT(models.PositiveIntegerField()) ' –

+0

只需将它们转换为整数:'(int(a)* 1000)/ int(b)' –

此错误表示您试图乘以(*)的对象类型是不同的对象,您不能将PositiveIntegerFieldint相乘。您将PositiveIntegerField对象与int对象混合在一起。通过在类中定义__mul__运算符重载方法,您可以使PositiveIntegerField出现在乘法表达式中,因此当带有乘法表达式的PositiveIntegerField的实例出现时,Python会自动重载__mul__方法。在蟒蛇2.X __coerce__被调用时,不同类型的对象出现在这样的表达式,以强制它们到一个共同的类型。不过,建议不要使用__coerce__

可以在数学运算中使用的一些类使用__int__返回一个整数,表示其值在需要的时候:

class Num: 
    def __int__(self): 
     return self.value 

int(Num()) * 20 
+0

我的答案中有任何错误吗?我看到了投票。 – direprobs

问题是你在模型类的创建时间打电话calculation_of_components,当这些领域还没有取得任何价值。

您可以通过no_modules解决这个property所以calculation_of_components没有得到在创建模型类的调用时的字段没有值:

class Plant(models.Model): 
    nominal_power = models.PositiveIntegerField() 
    module_nominal_power = models.PositiveIntegerField() 

    def calculation_of_components(self, a, b): 
     return int((a*1000)/b) 

    @property 
    def no_modules(self): 
     return self.calculation_of_components(self.nominal_power, self.module_nominal_power) 

然后,您可以访问no_modules像常规型号领域:

plnt = Plant(...) 
plnt.no_modules 

专业提示:你可以使用整数除法//在计算并避免拨打电话inta * 1000 // b

+0

我试过你的解决方案,但是当我尝试在我的views.py **植物中调用no_modules = Plant.objects.filter(user = request.user)** ** total_no_modules = Plant.objects.filter(user = request。用户).aggregate(sum = Sum('plants.no_modules'))**我得到**异常类型:FieldError ** – George

+0

@George您可以像使用模型字段一样使用它。如果你想要,你可以将它定义为'IntegerField'并在保存模型时赋值。 –

+0

我该怎么做? – George

第一项:calculation_of_components是静态类方法。

在您的代码中no_modules是功能calculation_of_components的结果。也许你需要一个函数:

class Plant(models.Model): 
    nominal_power = models.PositiveIntegerField() 
    module_nominal_power= models.PositiveIntegerField() 

    @staticmethod  
    def calculation_of_components(a, b): 
     return int((a*1000)/b) 

    def no_modules(self): 
     return self.calculation_of_components(self.nominal_power, self.module_nominal_power)