How to limit the maximum value of a numeric field in a Django model? How to limit the maximum value of a numeric field in a Django model? python python

How to limit the maximum value of a numeric field in a Django model?


You can use Django's built-in validators

from django.db.models import IntegerField, Modelfrom django.core.validators import MaxValueValidator, MinValueValidatorclass CoolModelBro(Model):    limited_integer_field = IntegerField(        default=1,        validators=[            MaxValueValidator(100),            MinValueValidator(1)        ]     )

Edit: When working directly with the model, make sure to call the model full_clean method before saving the model in order to trigger the validators. This is not required when using ModelForm since the forms will do that automatically.


You could also create a custom model field type - see http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields

In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.

The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.

This is working for me:

from django.db import modelsclass 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, verbose_name, name, **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)

Then in your model class, you would use it like this (field being the module where you put the above code):

size = fields.IntegerRangeField(min_value=1, max_value=50)

OR for a range of negative and positive (like an oscillator range):

size = fields.IntegerRangeField(min_value=-100, max_value=100)

What would be really cool is if it could be called with the range operator like this:

size = fields.IntegerRangeField(range(1, 50))

But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...


from django.db import modelsfrom django.core.validators import MinValueValidator, MaxValueValidatorsize = models.IntegerField(validators=[MinValueValidator(0),                                       MaxValueValidator(5)])