Django 模型对象什么时候初始化?

When are Django model objects initialized?

我在 Python 和 Django 中遇到了一个有趣的问题。 我认为只需输入我的代码,您就会得到我想要做的事情。

views.py:

def ingredients(request):
    objects = Ingredient.objects.all()[:50]
    return render(request, 'template.html', {'objects': objects}

models.py:

class Ingredient(models.Model):
    stock_by = models.IntegerField(null=False)
    unit = ""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        unit_type = {
            1: 'Units',
            2: 'Kilograms',
            3: 'Litters'
        }
        self.unit = unit_type[IntegerField.to_python(self.cost_by)]

错误:

TypeError at /Ingredient/
to_python() missing 1 required positional argument: 'value'

(值为 None)。

init.py (Django 框架class):

class IntegerField(field):
    def to_python(self, value):
        if value is None:
            return value
        try:
            return int(value)
        except (TypeError, ValueError):
            raise exceptions.ValidationError(
                self.error_messages['invalid'],
                code='invalid',
                params={'value': value},
        )

我想我想要达到的目标很清楚。只是一个字符串属性,它将采用单位值的名称(由 db 中的整数表示)。

to_python 是一个实例方法,您必须从实例中调用它,而不是 class.

IntegerField().to_python(self.cost_by)