我的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
我应该提供什么论点?
class Ingredient(models.Model):
cost_by = .....
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
如果在包含值到名称映射的字段中定义choices
,则将在该字段的任何ModelForm
中呈现一个选择字段,并且将在模型上生成一个方法来获取其显示名称所选值get_<field_name>_display()
get_<field_name>_display()
像这样使用
class Ingredient(models.Model):
COST_BY_CHOICES = (
(1, 'Units'),
(2, 'Kilograms'),
(3, 'Litters'),
)
cost_by = models.IntegerField(choices=COST_BY_CHOICES)