django 1.11 makemigration错误与自定义范围字段

时间:2017-05-18 14:15:35

标签: python django validation django-migrations

在djangosnippets我找到了IntegerRangeField(https://djangosnippets.org/snippets/3016/

的示例
from django.core.validators import MaxValueValidator, MinValueValidator
from django.db import models


class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        validators = []
        if isinstance(max_value, int):
            validators.append(MaxValueValidator(max_value))
        if isinstance(min_value, int):
            validators.append(MinValueValidator(min_value))
        models.IntegerField.__init__(
            self,
            verbose_name,
            name,
            validators=validators,
            **kwargs
        )

def formfield(self, **kwargs):
    defaults = {'min_value': self.min_value, 'max_value':self.max_value}
    defaults.update(kwargs)
    return super(IntegerRangeField, self).formfield(**defaults)

我的模特:

class MyModel (models.Model):
    .....
    automatic_logout_value = IntegerRangeField (min_value=5, max_value=1440, 
                               blank=True, null=True, default=30)

启动" python manage.py makemigrations"我收到错误:

c:\python34\lib\site-packages\django\db\migrations\state.py line 437, in from_model 
e,
TypeError: Couldn't reconstruct field automatic_logout_value on myApp.myModel:
__init__ () got multiple values for keyword 'validators'

任何想法代码都有问题吗? 谢谢!

2 个答案:

答案 0 :(得分:0)

您必须从validators中弹出kwargs。默认情况下它是一个元组,因此您需要将其转换为列表,以便您可以追加项目。

def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
    self.min_value, self.max_value = min_value, max_value
    validators = list(kwargs.pop('validators'))
    ...

答案 1 :(得分:0)

class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        models.IntegerField.__init__(self, *args, **kwargs)
        if isinstance(max_value, int):
            self.validators.append(MaxValueValidator(max_value))
        if isinstance(min_value, int):
            self.validators.append(MinValueValidator(min_value))

你可以试试这段代码吗,希望这有帮助