[Django]-How do I enforce a positive number on my Python/Django model field?

3👍

Unfortunately there is no PositiveFloatField in Django, but you can use MinValueValidator.

MinValueValidator is implemented like this:

class MinValueValidator(BaseValidator):
    message = _('Ensure this value is greater than or equal to %(limit_value)s.')
    code = 'min_value'

    def compare(self, a, b):
        return a < b  # super simple.

Append the validator to your float field.

class YourModel(models.Model):
    po_float = models.FloatField(validators=[MinValueValidator(0)]

m = YourModel(po_float=-1)
m.clean_fields()  # raise ValidationError

Note: Django validation does not run automatically. So you must run obj.clean_fields() or obj.clean(). Check this doc.

👤Jrog

0👍

Old post, but in case anyone is looking, add a CheckConstraint to the model.Meta to define the DB constraint. A MinValueValidator should be used, (as discussed in other answers) to catch invalid values before attempting to save them to DB.

So a complete solution to OP might be something like:

from django.core.validators import MinValueValidator

class ArticleStat(models.Model):
    ...
    score = models.FloatField(default=0, null=False, MinValueValidator(0))

class Meta:
    constraints = [
        models.CheckConstraint(check=models.Q(score__gte=0), name="score_gte_0"),
    ]

Leave a comment