Django

Querying the Models

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:

python
from django.db import models

class Book(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=100)
published_year = models.IntegerField()

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:

python
books = Book.objects.all()

This returns a QuerySet of all Book instances.


2. Filter Records

Get books by a specific author:

python
books_by_author = Book.objects.filter(author="J.K. Rowling")

You can chain filters to narrow down results.


3. Get a Single Object

Retrieve one object matching the criteria:

python
book = Book.objects.get(id=1)

⚠️ Raises DoesNotExist if not found, or MultipleObjectsReturned if multiple match.


4. Exclude Records

Exclude certain records:

python
non_rowling_books = Book.objects.exclude(author="J.K. Rowling")

5. Ordering Results

Order by published year:

python
books_ordered = Book.objects.order_by('published_year') # Ascending
books_ordered_desc = Book.objects.order_by('-published_year') # Descending

Advanced Filtering

Django supports complex lookups using field lookups:

  • icontains: Case-insensitive contains

python
Book.objects.filter(title__icontains="harry")
  • gte / lte: Greater than or equal / less than or equal

python
Book.objects.filter(published_year__gte=2000)
  • in: Filter by list of values

python
Book.objects.filter(author__in=["J.K. Rowling", "Tolkien"])

Aggregations and Counts

Get count of books:

python
count = Book.objects.count()

Aggregate example — average published year:

python
from django.db.models import Avg

avg_year = Book.objects.aggregate(Avg('published_year'))
print(avg_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'))

Leave a Reply

Your email address will not be published. Required fields are marked *