What do defer() and only() do, and when would you use them?
Last updated
only()loads just the named fields (plus the PK), whiledefer()loads everything except the named fields, such as large text or blob columns.Accessing a skipped field triggers an extra query per object, which can reintroduce N+1 problems.
Use them only when skipped columns are large and genuinely unused on that code path.
- https://docs.djangoproject.com/en/6.1/ref/models/querysets/
- https://docs.djangoproject.com/en/6.1/topics/db/optimization/
- https://testdriven.io/blog/django-query-optimization/
- https://alpeshkumar.com/n1-problem-in-django/
- https://dev-flow.io/en/posts/django-orm-defer-only-prefetch/
- https://dev.to/alansomathew/understanding-django-models-and-orm-a-complete-production-guide-34o6
- https://goodspace.ai/interview-questions/django
- https://www.reddit.com/r/django/comments/w5hlnt/does_defer_and_only_methods_in_queryset_helps_in/