Issue
I have a django model,
class MyModel(models.Model)
qty = model.IntegerField()
where I want to set constraint for qty
something like this, >0 or <0,i.e the qty
can be negative or positive but can not be 0.
Is there any straight forward way to do this in Django?
Solution
You can use Django's built-in validators -
from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator
class MyModel(models.Model):
qty = models.IntegerField(
default=1,
validators=[MaxValueValidator(100), MinValueValidator(1)]
)
NOTE:
- The validators will not run automatically when you save a model, but if you are using a ModelForm, it will run your validators on the fields that are included in the form. Check this link for more info.
- To enforce constraints on a database level refer to maertejin's answer below.
Answered By - JRodDynamite
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.