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'
我怎样才能解决这个问题?
此错误表示您试图乘以(*)的对象类型是不同的对象,您不能将PositiveIntegerField
与int
相乘。您将PositiveIntegerField
对象与int
对象混合在一起。通过在类中定义__mul__
运算符重载方法,您可以使PositiveIntegerField
出现在乘法表达式中,因此当带有乘法表达式的PositiveIntegerField
的实例出现时,Python会自动重载__mul__
方法。在蟒蛇2.X __coerce__
被调用时,不同类型的对象出现在这样的表达式,以强制它们到一个共同的类型。不过,建议不要使用__coerce__
。
可以在数学运算中使用的一些类使用__int__
返回一个整数,表示其值在需要的时候:
class Num:
def __int__(self):
return self.value
int(Num()) * 20
我的答案中有任何错误吗?我看到了投票。 – 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
专业提示:你可以使用整数除法//
在计算并避免拨打电话int
:a * 1000 // b
我试过你的解决方案,但是当我尝试在我的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
@George您可以像使用模型字段一样使用它。如果你想要,你可以将它定义为'IntegerField'并在保存模型时赋值。 –
我该怎么做? – 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)
一种方法是你可以转换'PositiveIntegerField'回'int':'nominal_power = INT(models.PositiveIntegerField())''module_nominal_power = INT(models.PositiveIntegerField()) ' –
只需将它们转换为整数:'(int(a)* 1000)/ int(b)' –