在IntegerRangeField中设置范围

时间:2017-03-13 13:15:54

标签: django django-models django-postgresql

我有一个模特:

from django.contrib.postgres.fields import IntegerRangeField

class Album(models.Model):
    rating = IntegerRangeField(default=0)

我想为默认验证目的设置最大值和最小值。已有answer,但验证不会自动运行。

那么如何在rating字段中设置最小值和最大值?

1 个答案:

答案 0 :(得分:3)

如果您的问题仅与验证有关,那么您可以在models.py中全局预定义这样的验证器



from django.db import models

from django.core.exceptions import ValidationError

def validate_range(value):
    if condition:  # Your desired conditions here
        raise ValidationError('%s some error message' % value)`

#And call them in your models wherever you require.

class MyModel(models.Model):
    field = models.IntegerField(validators=[validate_range])




如果您只想使用IntegerRangeField,那么这可能会有所帮助



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)