'0 value in Django PositiveIntegerField?

Can a field of type models.PositiveIntegerField contain a 0 value? I'm doing something like:

points = models.PositiveIntegerField()

Thanks,

I know I should try it myself, but I haven't a Django environment here.



Solution 1:[1]

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.

Solution 2:[2]

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]
)

Solution 3:[3]

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

Solution 4:[4]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tony
Solution 2 Vaibhav Mule
Solution 3 Pastor Emmanuel
Solution 4