【问题标题】:When are Django model objects initialized?Django 模型对象何时初始化?
【发布时间】:2020-06-19 18:59:04
【问题描述】:

我在使用 Django 的 Python 中遇到了一个有趣的问题。 我想只要输入我的代码,你就会得到我想要做的事情。

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'

(值为无)。

init.py(Django 框架类):

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 中的整数表示)。

【问题讨论】:

    标签: python django model integer init


    【解决方案1】:

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

    IntegerField().to_python(self.cost_by)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 2013-03-07
      • 2013-06-27
      相关资源
      最近更新 更多