覆盖Django模型初始化方法

2024-06-16 11:14:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我的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

我应该提供什么论据


Tags: 项目django模型self声明byinitmodels
3条回答

如果在包含值到名称映射的字段上定义choices,则将在该字段的任何ModelForm中呈现一个选择字段,并在模型上生成一个方法,以获取所选值的显示名称^{}

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())

我在这里发现的问题是,您没有将*args**kwargs传递给模型的__init__()和超级的__init__()

class Ingredient(models.Model):
    def __init__(self, *args, **kwargs):
        super(Ingredient, self).__init__(*args, **kwargs)
        # etc
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 

相关问题 更多 >