我得到__init __()在IntegerField上至少需要2个参数(给定1个)

时间:2015-04-21 23:21:10

标签: python django django-models

这是我的models.py 我在 init def

中得到的论证还不够

我知道有很多类似的问题,但我无法在那里找到解决方案。

class ExpField(models.FloatField):

    def __init__(self, *args, **kwargs):
        # Have a default "default" set to 0.
        if kwargs.get('default') is None:
            kwargs['default'] = 0

        super(ExpField, self).__init__(*args, **kwargs)


class LevelField(models.IntegerField):

    def __init__(self, exp_field, *args, **kwargs):
        # Have a default "default" set to 1.
        if kwargs.get('default') is None:
            kwargs['default'] = 1

        self.exp_field = exp_field

        super(LevelField, self).__init__(*args, **kwargs)

class Skills(models.Model):
    attack_exp = ExpField()
    attack = LevelField(exp_field=attack_exp)

我正在

TypeError: Couldn't reconstruct field attack on highscores.Skills: __init__() takes at least 2 arguments (1 given)

不确定是什么问题。

这是完整的痕迹

 [22/04/15 05:31:12][Raghav's:Runescape]$ python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/Library/Python/2.7/site-packages/django/core/management/base.py", line 441, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.7/site-packages/django/core/management/commands/makemigrations.py", line 99, in handle
    ProjectState.from_apps(apps),
  File "/Library/Python/2.7/site-packages/django/db/migrations/state.py", line 166, in from_apps
    model_state = ModelState.from_model(model)
  File "/Library/Python/2.7/site-packages/django/db/migrations/state.py", line 343, in from_model
    e,
TypeError: Couldn't reconstruct field attack on highscores.Skills: __init__() takes at least 2 arguments (1 given)

1 个答案:

答案 0 :(得分:2)

从构造函数的签名中删除位置exp_field参数,并从kwargs dict中获取字段:

class LevelField(models.IntegerField):

    def __init__(self, *args, **kwargs):
        if kwargs.get('default') is None:
            kwargs['default'] = 1
        self.exp_field = kwargs.pop('exp_field', None)
        super(LevelField, self).__init__(*args, **kwargs)