0
0
DjangoConceptBeginner · 3 min read

IntegerField in Django: Definition, Usage, and Examples

IntegerField in Django is a field type used in models to store whole numbers (integers) in the database. It ensures that only integer values are saved and provides validation automatically.
⚙️

How It Works

Think of IntegerField as a special container in your Django model that only accepts whole numbers, like the number of apples in a basket. When you create a model with an IntegerField, Django makes sure that the database column stores only integers and rejects anything else, like text or decimals.

This is similar to how a form input might only accept numbers, preventing mistakes early. Behind the scenes, Django uses this field to generate the right database column type (like INTEGER in SQL) and adds checks when saving data to keep your data clean and consistent.

💻

Example

This example shows a simple Django model with an IntegerField to store a person's age.

python
from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=100)
    age = models.IntegerField()

# Creating a new person instance
person = Person(name='Alice', age=30)
person.save()

# Accessing the age
print(person.age)
Output
30
🎯

When to Use

Use IntegerField whenever you need to store whole numbers in your database through Django models. Common examples include:

  • Counting items, like number of products in stock
  • Storing ages, years, or quantities
  • Tracking scores or rankings

It is not suitable for decimal numbers or very large numbers beyond typical integer limits. For decimals, use DecimalField, and for bigger numbers, consider BigIntegerField.

Key Points

  • IntegerField stores whole numbers only.
  • Django validates input to ensure only integers are saved.
  • It maps to an INTEGER column in the database.
  • Use it for counts, ages, or any integer data.
  • Not for decimals or very large numbers.

Key Takeaways

IntegerField is for storing whole numbers in Django models.
It automatically validates that only integers are saved to the database.
Use it for counts, ages, or any data that must be an integer.
For decimals or large numbers, use other field types like DecimalField or BigIntegerField.