Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set a default, max and min value for an integerfield Django?

from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator  class Match(models.Model):              .              .              .              overs = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(100)]) 

I've tried using the PositiveIntegerField but I believe that you cannot set a max value for that through Django - I'm not sure.

like image 509
Rajat Rasal Avatar asked Feb 23 '17 20:02

Rajat Rasal


People also ask

What does default do in Django?

default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created. null: If True , Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string).

What is the default primary key in Django?

If you don't specify primary_key=True for any fields in your model, Django will automatically add an IntegerField to hold the primary key, so you don't need to set primary_key=True on any of your fields unless you want to override the default primary-key behavior. For more, see Automatic primary key fields.


1 Answers

PositiveIntegerField ensures no integer less than 0 will be accepted. Your validators seem to handle the minimum and maximum values correctly. All you are missing is default for the default value. So something like

overs = models.PositiveIntegerField(default=10, validators=[MinValueValidator(1), MaxValueValidator(100)]) 
like image 71
Tom Avatar answered Sep 17 '22 17:09

Tom