Querying the Models in Django: Fetching Data Made Easy
One of Django’s greatest strengths is its built-in Object-Relational Mapping (ORM), which lets you interact with your database using Python code instead of raw SQL.
In this post, you’ll learn how to query Django models to retrieve, filter, and manipulate data effortlessly.
️ What Are Django Models?
Models are Python classes that define the structure of your database tables.
Example:
Once your model is defined and migrated, Django creates the corresponding database table.
Basic Queries Using the ORM
1. Get All Records
Retrieve all objects from a model:
This returns a QuerySet of all Book instances.
2. Filter Records
Get books by a specific author:
You can chain filters to narrow down results.
3. Get a Single Object
Retrieve one object matching the criteria:
⚠️ Raises DoesNotExist
if not found, or MultipleObjectsReturned
if multiple match.
4. Exclude Records
Exclude certain records:
5. Ordering Results
Order by published year:
Advanced Filtering
Django supports complex lookups using field lookups:
-
icontains: Case-insensitive contains
-
gte / lte: Greater than or equal / less than or equal
-
in: Filter by list of values
Aggregations and Counts
Get count of books:
Aggregate example — average published year:
️ Using QuerySets Efficiently
-
QuerySets are lazy: no database hits until you iterate or evaluate them.
-
Chain filters and orderings before evaluating to optimize queries.
Summary Cheat Sheet
Task | ORM Syntax |
---|---|
Get all objects | Model.objects.all() |
Filter objects | Model.objects.filter(field=value) |
Get one object | Model.objects.get(field=value) |
Exclude objects | Model.objects.exclude(field=value) |
Order results | Model.objects.order_by('field') |
Count objects | Model.objects.count() |
Aggregations | Model.objects.aggregate(Avg('field')) |