0

I have a model:

from django.contrib.postgres.fields import IntegerRangeField

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

I want to set maximum and minimum value for default validation purpose. There is already an answer , but that validation will not run automatically.

So How to set a min and max value in the rating field ?

Community
  • 1
  • 1
pyprism
  • 2,928
  • 10
  • 46
  • 85
  • 1
    Possible duplicate of [Django IntegerRangeField Validation failing](http://stackoverflow.com/questions/29460309/django-integerrangefield-validation-failing) – Nrzonline Mar 13 '17 at 13:19

1 Answers1

3

If your problem is only about validations then you can predefine a validator like this globally in 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])

If you want to use only IntegerRangeField then this might be helpful

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)
Avinash Bakshi
  • 319
  • 4
  • 11