[Django]-0 value in Django PositiveIntegerField?

39👍

Yes, it can. It is debatable whether it should–there is a longstanding bug report: http://code.djangoproject.com/ticket/7609

8👍

For those looking to exclude the 0, it’s easy to write a validator for that.

def validate_nonzero(value):
    if value == 0:
        raise ValidationError(
            _('Quantity %(value)s is not allowed'),
            params={'value': value},
        )

and then use it as such

fill_qty = models.PositiveIntegerField(
  default=0,
  validators=[MaxValueValidator(1000000), validate_nonzero]
)
👤Shadi

6👍

Yes.

The model field reference says so. For completeness, also quoted here:

PositiveIntegerField

class PositiveIntegerField([**options])

Like an IntegerField, but must be either positive or zero (0). The value 0 is accepted for backward compatibility reasons.

4👍

Well by the definition of a Positive Integer, it shouldn’t accept a zero value, but django actually considers it in the sense of none-negative number which is zero inclusive. So, Yes it can accept a zero value

3👍

Yes, "PositiveIntegerField" can contain "0" value.

For example, I defined the model "Point" as shown below:

# "myapp/models.py"

from django.db import models

class Point(models.Model):
    points = models.PositiveIntegerField()

Then, run this command below:

python manage.py makemigrations && python manage.py migrate

Now, I opened "db.sqlite3" then as you can see, "CHECK("points" >= 0)" is set to "points" field which means "PositiveIntegerField" can contain "0" value:

enter image description here

Leave a comment