Lightweight Queries: Using defer() and only()
By default, Django loads every field of a model instance. This is convenient but wasteful if you only need the title of a blog post and not its 5,000-word content body. To optimize this, use `defer('field_name')` to tell Django to skip loading specific heavy fields until they are explicitly accessed. Conversely, use `only('field_name')` when you want to load *only* a specific subset of fields.
Scenario 1: Using defer() for large text fields
Best for list views where you don't need the heavy content body.
# Loads all fields EXCEPT 'content' and 'meta_data'
# Useful for listing 50 blog posts quickly
posts = BlogPost.objects.defer('content', 'meta_data').all()
Scenario 2: Using only() for dropdowns
Load ONLY the ID and Name. Warning: Accessing other fields triggers new queries.
# Loads ONLY 'id' and 'name'
# Perfect for populating a <select> dropdown
users = User.objects.only('id', 'name').all()