Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a field stores percentage value in a model. How can I limit the possible values to 0-100 range in a more strict way than the model validators do1?

Notes

  1. Model validators will not be run automatically when you save a model, but if you're using ModelForms
like image 704
ancho Avatar asked Sep 05 '25 01:09

ancho


1 Answers

You should use a validator.

from django.db import models
from django.core.validators import MaxValueValidator

class MyModel(models.Model):
    percent_field = models.PositiveIntegerField(min_value=0, validators=[MaxValueValidator(100),])

Personally, I would rather use a Float for storing a percentage, and use the 0-1 range. The validator should work in a similar fashion.

like image 88
elpaquete Avatar answered Sep 06 '25 22:09

elpaquete