覆盖Django模型__init__方法 [英] Overwrite Django model __init__ method
问题描述
我的Django项目的成分模型有一个 IntegerField
,它声明该成分库是按重量,单位还是垃圾来管理的.
The Ingredient model of my Django project has an IntegerField
which declares if this ingredient stock is managed by weight, units, or litters.
尽管数据库具有其 integer
值,但我必须显示其名称.而且我认为最好覆盖Python类的 __ init __
方法,而不是遍历每种成分并设置其值,但我不知道怎么做.
Although the database has its integer
value I have to display its name. And instead of looping over every ingredient and setting its value, I thought it was better to overwrite the __init__
method of the Python class, but I don't get how.
models.py:
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...
到目前为止,我已尝试过此操作,但出现以下错误:
So far I tried with this, but I'm getting the following error:
__init__() takes 1 positional argument but 0 were given
我应该提供什么论点?
推荐答案
如果在包含值到名称映射的字段上定义 choices
,那么您将获得以任何呈现的select字段> ModelForm
,您将在模型上生成一个方法,以获取所选值的显示名称
If you define choices
on a field that contains the value to name mapping then you will get a select field rendered in any ModelForm
for that field and you will get a method generated on the model to get the display name for the selected value 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)
像这样使用
ingredient = Ingredient(cost_by=1)
print(ingredient.get_cost_by_display())
这篇关于覆盖Django模型__init__方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!