python / expert
Snippet
Django QuerySet Optimization with only() and defer() for Selective Field Loading
Django's only() method specifies which fields to load immediately, deferring all others as deferred fields that are fetched on demand when accessed. The defer() method specifies fields to exclude from the initial query, useful for large text fields or JSON fields that are rarely needed immediately. Combining these with select_related() for foreign keys and ordering with slicing optimizes both the query structure and result set size. The values_list() with flat=True returns simple Python values instead of model instances for maximum performance when you don't need full objects.
snippet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from django.db import modelsclass Article(models.Model):title = models.CharField(max_length=200)content = models.TextField()summary = models.TextField()author = models.ForeignKey('Author', on_delete=models.CASCADE)created_at = models.DateTimeField(auto_now_add=True)updated_at = models.DateTimeField(auto_now=True)metadata = models.JSONField(default=dict)# Fetch only required fields - reduces memory and query timetitles_and_dates = Article.objects.only('title', 'created_at').filter(author__name__icontains='python')# Defer heavy fields that are rarely accessed immediatelyarticles_with_deferred_content = Article.objects.defer('content', 'metadata').select_related('author').all()# Combine with ordering and slicingrecent_titles = Article.objects.only('title', 'created_at').order_by('-created_at')[:10]# Chain with values() for dictionaries instead of model instancesauthor_names = Article.objects.values_list('author__name', flat=True).distinct()[:5]
django
Breakdown
1
Article.objects.only('title', 'created_at')
only() fetches specified fields immediately, deferring all others
2
articles_with_deferred_content = Article.objects.defer('content', 'metadata')
defer() excludes specified fields from initial query payload
3
.select_related('author')
select_related() performs SQL JOIN to fetch related Author in same query
4
.order_by('-created_at')[:10]
Orders by created_at descending and limits to 10 results
5
values_list('author__name', flat=True)
values_list() returns tuples, flat=True returns simple list of values
6
.distinct()[:5]
distinct() eliminates duplicates before slicing to 5 results