我在Django 4.0.2在python 3.10.2
我读过如何转换一个模型。integerfield()到一个整数(海报实际上需要复制构造函数)。我还搜索了谷歌
但是没有用。
我想做的是:
#In app/models.py
class Foo:
a1 = models.IntergeField()
a2 = models.IntergeField()
#....
#many else
b1 = convertToInt(a1) * 3 + convertToInt(a2) *4 + convertToInt(a7) #calc by needing
b2 = convertToInt(a2) * 2 + convertToInt(a3) + convertToInt(a5) #calc by needing
#....
#many else
#b(b is price actually) will be used in somewhere else.Its type need be int for programmer-friendly using
任何建议吗?
注:英语不是我的第一语言。请原谅我的语法错误。
编辑1:
如果只是a1 * 3
,我将收到
TypeError: unsupported operand type(s) for *: 'IntegerField' and 'int'
我想解释一下为什么上面附加的链接中的解决方案不起作用
第一个答案使用:
class Foo(models):
nombre_etudiant = models.IntergeField()
place_disponible =models.IntegerField(blank=True,null=True)
def __init__(self,*args,**kwargs):
super(Foo, self).__init__(*args, **kwargs)
if self.place_disponible is None:
self.place_disponible = self.nombre_etudiant
我仍然不能将num乘以n,代码只是复制。我仍然无法获得int
类型的值。
第二个解
class MyModel(models):
nombre_etudiant = models.IntergeField()
place_disponible =models.IntegerField()
def save(self, *args, **kwargs):
if not self.place_disponible:
self.place_disponible = int(nombre_etudiant)
super(Subject, self).save(*args, **kwargs)
self.place_disponible = int(nombre_etudiant)
这将捕获异常,如TypeError: int() argument must be a string, a bytes-like object or a real number, not 'IntegerField'
由于您在注释中表示不需要存储派生属性,因此我提出以下解决方案。这里每次都会计算属性,您可以像使用a1
和a2
属性一样使用它们。
class Foo(models.Model):
a1 = models.IntegerField()
a2 = models.IntegerField()
@property
def b1(self):
return self.a1*3 + self.a2*4 # + ...
@property
def b2(self):
return self.a2*3 + self.a3 # + ...