11.4 Sessions, auth, and the admin
Permission checks, groups, and ContentType caching
How does PermissionsMixin cache every permission for the lifetime of a user object, and why does ContentTypeManager keep a process-wide lookup cache?
Every model in Django automatically receives four database rows in "auth_permission" after migrations run (add_<model>, change_<model>, delete_<model>, view_<model>), each linked to its model via a foreign key to "django_content_type". When a view, template ("{% if perms), or Admin page checks "user, Django avoids querying "auth_permission" over and over by caching permissions directly on the Python User instance — a design that makes repeated checks free (0 SQL) while introducing one famous mid-request staleness trap.
Per-instance permission caching in PermissionsMixin
Open PermissionsMixin:
if self.is_active and self.is_superuser:
return True
return _user_has_perm(self, perm, obj)
Active superusers short-circuit immediately with zero database queries. Every other user delegates to _user_has_perm, which loops over "AUTHENTICATION_BACKENDS" returning True as soon as any backend approves (or False immediately if any backend raises PermissionDenied, mirroring authenticate).
Now look inside ModelBackend and ModelBackend:
- If
"not user_obj,.is_active" "user_obj, or.is_anonymous" "obj is not None"(becauseModelBackenddoes not implement per-object row permissions), it returns an emptyset()without touching the database. - On the first permission check for an active user,
ModelBackendloads every direct user permission (.get_all_permissions "user_obj) into.user_permissions .all()" "_user_perm_cache"(query 1), loads every group permission ("Permission) into.objects .filter(group__in=user_obj .groups .all())" "_group_perm_cache"(query 2), and stores their union ({"app_label) on.codename", ...} "user_obj!._perm_cache" - Every subsequent call to
has_perm,has_perms, orhas_module_permsduring that request simply tests membership in that Pythonset(0SQL queries!).
Here is the trap that bites both views and unit tests: all three caches live directly on the User Python instance for its entire lifetime! If a view or test checks "ada (populating "ada), then grants the permission or adds "ada" to a "desk-editors" Group in the database, and then calls "ada again on the same Python object, Django still returns False! Calling "ada will not fix it either, because refresh_from_db() only reloads model fields, leaving "_user_perm_cache", "_group_perm_cache", and "_perm_cache" untouched! To see newly granted permissions immediately, you must fetch a fresh User instance from the database ("User).
Process-wide ContentTypeManager._cache
Permissions, Admin "LogEntry" audit records, and GenericForeignKey relations all need the primary key of a model’s "django_content_type" row. Querying "django_content_type" on every permission check or admin log write would flood the database with trivial lookups, so ContentTypeManager keeps a process-wide dictionary "_cache" scoped by database alias ("self.db").
Open ContentTypeManager:
key = (ct.app_label, ct.model)
self._cache.setdefault(using, {})[key] = ct
self._cache.setdefault(using, {})[ct.id] = ct
Notice the clever double-indexing: loading one ContentType via ContentTypeManager caches it under both (app_label, model_name) and its integer primary key "ct.id" — so a later ContentTypeManager returns the exact same in-memory object with 0 SQL queries! (In tests that flush or migrate tables mid-run, stale cached IDs can cause foreign-key errors, which is why ContentTypeManager exists and why Django’s test runner clears it automatically.)
Watch both "ada"'s per-instance "_perm_cache" staleness trap and ContentTypeManager returning the identical cached object at 0 SQL queries live on "desk/":
4. PermissionsMixin _perm_cache staleness and ContentType._cache
perm_cache: first_sql=2 repeat_sql=0 before=False repeat=False after_db_grant_same_obj=False fresh_obj=True
cached_attrs_on_user = ['_group_perm_cache', '_perm_cache', '_user_perm_cache']
contenttype_cache: cold_sql=1 warm_model_sql=0 warm_id_sql=0 same_obj=True
Look at line 21: first_sql=2 (direct + group permissions), repeat_sql=0, after_db_grant_same_obj=False (stale cache on "ada"!), and fresh_obj=True once re-queried.
We now have sessions, lazy users, password hashers, permissions, and ContentTypes in hand. Time to see how Django’s own flagship application — django — puts every internal layer of Chapters 1 through 11 to work, starting with startup registration and dynamic URL generation in AdminSite, autodiscover, and dynamic URLs.