我的 Django 项目的 Ingredient 模型有一个IntegerField
它声明该原料库存是否按重量、单位或窝数进行管理。
虽然数据库有它的integer
value 我必须显示它的名称。我认为最好覆盖每个成分并设置其值,而不是覆盖__init__
Python 类的方法,但我不明白如何实现。
模型.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
我应该提供什么论据?
如果你定义choices
在包含值到名称映射的字段上,您将获得一个以任何形式呈现的选择字段ModelForm
对于该字段,您将获得在模型上生成的方法来获取所选值的显示名称get_<field_name>_display() https://docs.djangoproject.com/en/3.0/ref/models/instances/#django.db.models.Model.get_FOO_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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)