ancho
ancho

Reputation: 1060

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

Upvotes: 4

Views: 8197

Answers (1)

elpaquete
elpaquete

Reputation: 241

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.

Upvotes: 10

Related Questions