[Fixed]-Django Models Number Field

34👍

One of the cool things about Django that it provides you with different types of models read about them here.

For your case try something like this

number = models.IntegerField()

You can read more about the IntegerField here

3👍

Player’s shirt numbers should need only positive numbers.

PositiveBigIntegerField allows values from 0 to 9223372036854775807:

number = models.PositiveBigIntegerField()

PositiveIntegerField allows values from 0 to 2147483647:

number = models.PositiveIntegerField()

PositiveSmallIntegerField allows values from 0 to 32767:

number = models.PositiveSmallIntegerField()

In addition, there are no "NegativeIntegerField", "NegativeBigIntegerField" and "NegativeSmallIntegerField" in Django.

0👍

There a number of fields rather than CharField in Django either in case of models or modelfields you use for forms:

In case of Integers you use: number = models.IntegerField()

or even

number = models.FloatField(), in case you want to represent price of a specific commodity.Its usefull in billing softwares.

There is also somemore like BigInteger field in case you wanted more nos

For detailed reference check:https://docs.djangoproject.com/en/1.11/ref/models/fields/

0👍

If you’re using serializers, you can use validators for these cases. For example, for a 10-digit CharField, you can have a validator like this :

def postalcode_validator(value):
    rule = re.compile(r'^\d{10}$')
    if not rule.search(value):
        raise serializers.ValidationError("Postal code format must be XXXXXXXXXX")
    return value

Then, you can use this validator with your serializer’s CharField:

# serializers.py
...
postal_code = serializers.CharField(validators=[postalcode_validator])

Moreover, validators can be used with model fields as well just like the above example.

Leave a comment