Performance: Why querysets are lazy and powerful
This concept affects database query execution timing and page load speed by delaying data fetching until necessary.
Jump into concepts and practice - no test required
users = User.objects.filter(is_active=True) for user in users: print(user.username)
all_users = list(User.objects.all()) for user in all_users: print(user.username)
| Pattern | Database Queries | Memory Usage | Blocking Time | Verdict |
|---|---|---|---|---|
| Eager loading with list() | 1 immediate query | High (loads all data) | Blocks rendering until done | [X] Bad |
| Lazy queryset iteration | Query runs on iteration | Lower (fetches as needed) | Non-blocking until data needed | [OK] Good |
filter() method returns a queryset and does not hit the database immediately.get() fetches a single object immediately, create() inserts data, and all() returns all objects but still lazy.qs = MyModel.objects.filter(active=True) print(qs.query) list(qs) print(qs.query)
qs.query shows the SQL query string without fetching data.list(qs) triggers the database query and fetches data.qs = MyModel.objects.filter(name='Bob') qs = qs.filter(age>30)
age__gt=30.filter() calls to build complex queries lazily.list() or other evaluation methods too early fetches data multiple times, which is inefficient.