Django Models & ORM
Django Models represent the structure of data stored in a database. They define fields, relationships, and behaviors of the data used in a Django application. Django provides a powerful ORM (Object Relational Mapping) system that allows developers to interact with the database using Python code instead of writing raw SQL queries.
The Django ORM simplifies database operations such as creating, retrieving, updating, and deleting data.
What is a Django Model?
A Django model is a Python class that represents a database table. Each attribute of the model represents a field in the table.
Django automatically generates database tables based on the models defined in the application.
Example of a Django Model
In this example:
- Post represents the database table.
- title, content, and created_at represent columns.
__str__()returns a readable representation of the object.
Common Django Model Fields
| Field Type | Description |
|---|---|
| CharField | Stores short text strings |
| TextField | Stores large text content |
| IntegerField | Stores integer values |
| FloatField | Stores decimal numbers |
| DateField | Stores date values |
| DateTimeField | Stores date and time values |
| BooleanField | Stores true or false values |
| EmailField | Stores email addresses |
Applying Database Migrations
After creating models, Django needs to generate database tables using migrations.
Step 1: Create migration files
Step 2: Apply migrations to the database
This will create database tables based on the models.
What is Django ORM?
The Django ORM allows developers to interact with the database using Python objects instead of SQL queries. This makes database operations easier, safer, and more readable.
With ORM, developers can perform CRUD operations using Python code.
Creating Records
This creates a new record in the database.
Retrieving Data
This retrieves all records from the Post table.
Filtering Data
This retrieves records matching specific conditions.
Updating Data
This updates a record in the database.
Deleting Data
This removes a record from the database.
Model Relationships
Django models support relationships between tables.
Foreign Key (One-to-Many)
Many-to-Many Relationship
One-to-One Relationship
Advantages of Django ORM
- No need to write raw SQL queries
- Improves code readability
- Provides database abstraction
- Prevents SQL injection vulnerabilities
- Works with multiple database engines
Conclusion
Django Models define the structure of database tables, while the Django ORM provides an easy way to interact with those tables using Python code. Together, they simplify database management and improve development productivity.
Understanding Django Models and ORM is essential for building dynamic web applications that interact with databases efficiently.
In the next tutorial, we will explore Django Views & URL Routing and learn how Django processes web requests and sends responses to users.

