A Django Model is a Python class that defines the structure and behavior of data stored in the database, acting as the definitive source of information about your data using Django’s Object-Relational Mapper (ORM).
Instead of writing raw SQL to create tables and manage data, you write Python classes. A Model represents a single database table, and its attributes represent the columns. Django automatically translates this class into the corresponding SQL.
- Define a class inheriting from
django.db.models.Model. - Define class attributes as fields (e.g.,
models.CharField). - Run
makemigrationsto generate migration files based on the model. - Run
migrateto apply the changes to the database schema. - Use the model’s Manager (e.g.,
Model.objects) to query the database.
graph TD A[Model Class in Python] -->|makemigrations| B(Migration File) B -->|migrate| C[(Database Table)]
Think of a Model as a blueprint or a mold. If you want to make toy cars (database rows), you first design the mold (the Model) specifying it has 4 wheels, a color, and a shape. Django uses this mold to stamp out data in the database.
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()- Subclasses
django.db.models.Model. - Fields map to database columns.
- Provides an automatic API to query the database.
- Built from: Django ORM — the system that powers models.
- Builds into: Django Migration — models generate migrations.
- Related: Django View — views interact with models.
- Related: Django Form — ModelForms are generated from models.
- Changing a model requires making and applying migrations; the database doesn’t magically update.
- N+1 query problems can occur if relationships are not queried efficiently using
select_relatedorprefetch_related.