我正在使用 python 3.10.2 中的 Django 4.0.2
我已经阅读了 How to convert a models.IntegerField() to an integer(海报实际上需要复制构造函数)。我搜索了谷歌。
但这无济于事。
我想做的是:
#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
有什么建议吗?
PS英语不是我的第一语言。请原谅我的语法错误。
如果只是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 # + ...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句