Categories
Python Answers

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

Spread the love

To limit the maximum value of a numeric field in a Python Django model, we can use MaxValueValidator and MinValueValidator.

For instance, we write

from django.db.models import IntegerField, Model
from django.core.validators import MaxValueValidator, MinValueValidator

class CoolModel(Model):
    limited_integer_field = IntegerField(
        default=1,
        validators=[
            MaxValueValidator(100),
            MinValueValidator(1)
        ]
     )

to add the limited_integer_field field into the CoolModel model.

We limit the value of limited_integer_field saved by calling MaxValueValidator with 100 to set the max limited_integer_field value to 100.

And we call MinValueValidator with 1 to set the min limited_integer_field to 1.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *