【问题标题】:Overwrite Django model __init__ method覆盖 Django 模型 __init__ 方法
【发布时间】: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


【解决方案1】:

如果您在包含值到名称映射的字段上定义 choices,那么您将在任何 ModelForm 中为该字段呈现选择字段,您将获得在模型上生成的方法以获取显示名称对于选定的值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())

【讨论】:

    【解决方案2】:
    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 
    

    【讨论】:

      【解决方案3】:

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

      class Ingredient(models.Model):
          def __init__(self, *args, **kwargs):
              super(Ingredient, self).__init__(*args, **kwargs)
              # etc
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-03-20
        • 1970-01-01
        • 1970-01-01
        • 2016-05-13
        • 2021-11-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多