from blog.models import Post
# Load only specific fields
posts = Post.objects.only('id', 'title', 'published_at')
for post in posts:
print(post.title) # No extra query
# print(post.content) # Would trigger extra query
# Exclude large fields
posts = Post.objects.defer('content', 'raw_content')
for post in posts:
print(post.title) # No extra query
# Accessing content would trigger query
# Combine with select_related
posts = Post.objects.select_related('author').only(
'id', 'title', 'author__username'
)
# For API responses
def get_post_list_data():
return Post.objects.only(
'id', 'title', 'slug', 'published_at', 'author_id'
).select_related('author').only(
'author__id', 'author__username'
)
The only() method loads specified fields only, while defer() excludes specified fields. This reduces data transfer and memory usage. I use only() when I need just a few fields from large models. For read-only displays, this prevents loading unnecessary data. I'm careful with deferred fields—accessing them causes additional queries. For JSON APIs, only() with serializer fields prevents over-fetching. I combine with select_related() for efficient joins. These optimizations are crucial for models with many or large fields.