Overwrite Django model __init__ method

限于喜欢 提交于 2021-02-10 22:41:11

问题


The Ingredient model of my Django project has an IntegerField which declares if this ingredient stock is managed by weight, units, or litters.

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:

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

What argument should I provide?


回答1:


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)

Used like this

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:


The problem I find here is that you did not pass *args and **kwargs to the Models's __init__() and to the super's __init__()

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


来源:https://stackoverflow.com/questions/60481894/overwrite-django-model-init-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!