Django models are used to define the structure of data that an application works with. A model is a Python class that usually represents a database table. Each model field represents a type of data stored in that table.
A Django model is a Python class used to describe data that an application needs to store and manage.
For example, a student model may contain:
Django normally maps a model to a database table.
Student Model
↓
students_student Table
The model defines the structure, while the database stores the actual records.
Models are normally defined inside the app's models.py file.
students/
├── models.py
├── views.py
├── admin.py
└── apps.py
Open models.py to create your application's models.
A basic Django model starts by importing Django's models module.
from django.db import models
The models module provides classes such as
CharField, IntegerField, and
DateField.
A model is created by defining a Python class that inherits from
models.Model.
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
Here, Student is the model name and name is a model
field.
The class represents the model.
class Student(models.Model):
pass
By inheriting from models.Model, the class becomes a Django model.
Fields define the type of information that the model stores.
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
email = models.EmailField()
Each field becomes a column in the corresponding database table.
CharField is commonly used for short text.
name = models.CharField(max_length=100)
The max_length argument defines the maximum length of the text.
Examples:
name = models.CharField(max_length=100)
city = models.CharField(max_length=50)
course = models.CharField(max_length=100)
IntegerField stores integer values.
age = models.IntegerField()
marks = models.IntegerField()
quantity = models.IntegerField()
It is useful for values such as age, quantity, and marks.
EmailField is designed for email addresses and provides email
validation behavior.
email = models.EmailField()
Example value:
student@example.com
BooleanField stores a true or false value.
is_active = models.BooleanField(default=True)
It can be useful for status values such as active/inactive.
DateField is used for date values.
admission_date = models.DateField()
It can store values representing dates such as admission dates or birthdays.
DateTimeField is used when both date and time are needed.
created_at = models.DateTimeField(
auto_now_add=True
)
This is commonly used for timestamps.
TextField is commonly used for larger amounts of text.
description = models.TextField()
It can be used for descriptions, comments, articles, or other long text.
DecimalField is useful for decimal values such as prices or fees.
fee = models.DecimalField(
max_digits=10,
decimal_places=2
)
Here, max_digits represents the total number of digits and
decimal_places represents digits after the decimal point.
A field can have a default value.
is_active = models.BooleanField(
default=True
)
If a value is not supplied when creating a record, Django can use the default value.
The null option controls whether the database can store
NULL for a field. The blank option is related to
validation and whether an empty value is allowed by forms.
phone = models.CharField(
max_length=15,
blank=True
)
These options have different purposes and should not be treated as identical.
Django automatically creates an ID field as the primary key when a model does not explicitly define one.
class Student(models.Model):
name = models.CharField(max_length=100)
The generated primary key uniquely identifies each database record.
A model can explicitly define a field as the primary key.
student_id = models.CharField(
max_length=20,
primary_key=True
)
Only one field can be the primary key of a model.
from django.db import models
class Student(models.Model):
name = models.CharField(
max_length=100
)
email = models.EmailField()
mobile = models.CharField(
max_length=15
)
age = models.IntegerField()
course = models.CharField(
max_length=100
)
is_active = models.BooleanField(
default=True
)
This model contains several fields for storing student information.
Django models can contain an inner Meta class to configure
additional model options.
class Student(models.Model):
name = models.CharField(
max_length=100
)
class Meta:
ordering = ['name']
The Meta class can control various model-level options.
The __str__() method can define how a model object is represented
as text.
class Student(models.Model):
name = models.CharField(
max_length=100
)
def __str__(self):
return self.name
This is especially useful when viewing objects in the Django admin interface.
After creating or changing a model, use makemigrations to create
migration files.
python manage.py makemigrations
Django examines model changes and creates migration instructions.
Use the migrate command to apply migrations to the database.
python manage.py migrate
This updates the database according to the migration files.
Django's Object-Relational Mapper, commonly called the ORM, allows Python code to work with database records.
For example:
Student.objects.all()
This can be used to retrieve Student records without writing a raw SQL query for this basic operation.
A model object can be created using Python code.
student = Student(
name="Rahul",
email="rahul@example.com",
age=20
)
student.save()
The save() method stores the object in the database.
The ORM provides QuerySets for retrieving model records.
students = Student.objects.all()
The returned QuerySet can contain multiple Student objects.
A single record can also be retrieved with appropriate ORM methods such as
get().
Models can be registered in admin.py so that administrators can
manage records through Django's admin interface.
from django.contrib import admin
from .models import Student
admin.site.register(Student)
After registration and login, the model can be available in the admin site.
Step 1: Define the model
from django.db import models
class Student(models.Model):
name = models.CharField(
max_length=100
)
email = models.EmailField()
age = models.IntegerField()
def __str__(self):
return self.name
Step 2: Create migrations
python manage.py makemigrations
Step 3: Apply migrations
python manage.py migrate
Step 4: Register the model
from django.contrib import admin
from .models import Student
admin.site.register(Student)
The model is now connected to Django's database and admin workflow.
Django models provide a convenient way to define and manage application data. They are Python classes that work with Django's ORM and database system.
models.py.models.Model.CharField stores text.IntegerField stores integer values.EmailField stores email-related values.DateField stores dates.DateTimeField stores dates and times.BooleanField stores true or false values.makemigrations and migrate after model changes.models.py.__str__() method provides a useful text representation of objects.makemigrations creates migration files.migrate applies migrations to the database.Question: Which file is normally used to define Django models?