0
0
Djangoframework~5 mins

Relationship query patterns in Django

Choose your learning style9 modes available
Introduction

Relationship query patterns help you get data connected between tables easily. They let you find related information without writing complex code.

You want to get all books written by a specific author.
You need to find all comments related to a blog post.
You want to list all orders made by a customer.
You want to filter users who have posted at least one article.
You want to access the profile details linked to a user.
Syntax
Django
Model.objects.filter(related_model__field=value)
Model.objects.get(pk=1).related_model_set.all()
Use double underscores (__) to follow relationships in queries.
Related objects can be accessed using the related model name plus '_set' by default.
Examples
Find all books where the author's name is 'Alice'.
Django
Book.objects.filter(author__name='Alice')
Get all books written by the author with primary key 1.
Django
author = Author.objects.get(pk=1)
author.book_set.all()
Find comments on posts with 'django' in the title (case-insensitive).
Django
Comment.objects.filter(post__title__icontains='django')
Get users whose linked profile has age 18 or older.
Django
User.objects.filter(profile__age__gte=18)
Sample Program

This example shows how to create an author and two books linked to her. Then it queries all books where the author's name is 'Alice' and prints their titles.

Django
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

# Sample usage
# Create an author and books
alice = Author.objects.create(name='Alice')
Book.objects.create(title='Django Basics', author=alice)
Book.objects.create(title='Advanced Django', author=alice)

# Query books by author name
books_by_alice = Book.objects.filter(author__name='Alice')

for book in books_by_alice:
    print(book.title)
OutputSuccess
Important Notes

Remember to use the related model's field names exactly as defined.

Using double underscores lets you go through multiple relationships, like book__author__name.

Accessing related objects backward uses relatedmodel_set unless you set related_name.

Summary

Relationship queries let you find connected data easily.

Use double underscores to follow links between models.

Access related objects forward and backward with simple patterns.