Database Query Optimization with only()
A snippet showing how to use only() in Django QuerySets.
# views.py
from .models import Product
from django.shortcuts import render
def list_products(request):
# Only fetch selected fields from the database for each product
products = Product.objects.only("id", "name", "price")
return render(request, "products/list.html", {"products": products})
Explanation:
- Fetches only selected columns; other fields deferred until accessed.
- Greatly improves performance when you only need a few fields from a large model.
- Category Performance & Optimization
- Total Views 175
- Last Modified 08 May, 2026
- Tags #performance #queries #optimization #only
Previous snippet
Template Fragment Caching
Next snippet