【发布时间】:2020-06-14 08:07:47
【问题描述】:
我的 Django 项目的成分模型有一个 IntegerField,它声明此成分库存是否按重量、单位或窝来管理。
虽然数据库有它的integer 值,但我必须显示它的名称。与其循环遍历每种成分并设置其值,我认为最好覆盖 Python 类的 __init__ 方法,但我不明白如何。
models.py:
class Ingredient(models.Model):
def __init__(self):
super(Ingredient, self).__init__()
if self.cost_by == 1:
self.cost_by = 'Units'
elif self.cost_by == 2:
self.cost_by = 'Kilograms'
elif self.cost_by == 3:
self.cost_by = 'Litters'
#...etc...
到目前为止,我尝试了这个,但我收到以下错误:
__init__() takes 1 positional argument but 0 were given
我应该提供什么论据?
【问题讨论】:
-
你怎么称呼你的成分?
-
Ingredient.objects.filter(account=account, brand=brand, name=name) -
也许你可以试试 def __str__(self): if self.cost_by == 1: self.cost_by = 'Units' elif self.cost_by == 2: self.cost_by = 'Kilograms' elif self .cost_by == 3: self.cost_by = 'Litters' return self.cost
-
我认为@iamcoder 指的是创建时间。你是如何创造成分的?顺便说一句,声明为方法怎么样?
-
是的,可能有一种方法,然后在迭代获取成分时,您可以操作整数字段
标签: python django class model init