What's the difference between `get()`, `filter()`, and `all()` on a queryset?
The difference between get, filter and all on a Django queryset, down to the Query object and the SQL each one emits. filter() and all() are lazy: each clones the underlying Query, adds conditions to the copy and returns a new QuerySet, so a chain of calls issues zero database queries until something iterates it and the whole chain compiles into one statement. get() is eager, applies a LIMIT 21 from MAXGETRESULTS so it can tell one row from many, and raises DoesNotExist or MultipleObjectsReturned instead of returning a set. Explains the resultcache that makes a second iteration free, why calling filter() on an evaluated queryset issues a fresh query rather than narrowing cached rows, and why all() on a queryset is the idiomatic refetch. Includes runnable Django code and real output, plus exists versus count versus len, first, and why two filter calls across a reverse foreign key add a second join and return different rows than one call.
Comentarii