🎸 Django Beginner

What is select_related and prefetch_related in Django?

Answer

Both methods optimize database queries for related objects, preventing the N+1 query problem: select_related: performs a SQL JOIN to fetch related objects in a single query. Works with ForeignKey and OneToOneField (forward relationships). articles = Article.objects.select_related("author", "category").all() — one SQL query with JOIN instead of N queries. Access: article.author.username (no extra query). Use for "to-one" relationships. prefetch_related: performs separate queries for each relationship and does Python-level joining. Works with ManyToManyField and reverse ForeignKey (one-to-many). articles = Article.objects.prefetch_related("tags", "comments").all() — 3 queries: one for articles, one for tags, one for comments. Django joins them in Python. Prefetch objects: customize prefetch queries: from django.db.models import Prefetch active_comments = Prefetch("comments", queryset=Comment.objects.filter(is_approved=True), to_attr="active_comments") articles = Article.objects.prefetch_related(active_comments). Access: article.active_comments. N+1 problem example: for article in Article.objects.all(): # N+1! print(article.author.username) # Extra query per article. Fix: Article.objects.select_related("author").all() — one query. Diagnosing: use Django Debug Toolbar to see all queries executed per request. Combination: Article.objects.select_related("author").prefetch_related("tags")