Django 6.1.3

11.4 Sessions, auth, and the admin

Permission checks, groups, and ContentType caching

How does PermissionsMixin.has_perm 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.newsroom.change_story %}"), or Admin page checks "user.has_perm('newsroom.change_story')", 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.has_perm:

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._get_permissions and ModelBackend.get_all_permissions:

  1. If "not user_obj.is_active", "user_obj.is_anonymous", or "obj is not None" (because ModelBackend does not implement per-object row permissions), it returns an empty set() without touching the database.
  2. On the first permission check for an active user, ModelBackend.get_all_permissions loads every direct user permission ("user_obj.user_permissions.all()") into "_user_perm_cache" (query 1), loads every group permission ("Permission.objects.filter(group__in=user_obj.groups.all())") into "_group_perm_cache" (query 2), and stores their union ({"app_label.codename", ...}) on "user_obj._perm_cache"!
  3. Every subsequent call to has_perm, has_perms, or has_module_perms during that request simply tests membership in that Python set (0 SQL 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.has_perm('newsroom.change_story')" (populating "ada._perm_cache = set()"), then grants the permission or adds "ada" to a "desk-editors" Group in the database, and then calls "ada.has_perm('newsroom.change_story')" again on the same Python object, Django still returns False! Calling "ada.refresh_from_db()" 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.objects.get(pk=ada.pk)").

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._add_to_cache:

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.get_for_model caches it under both (app_label, model_name) and its integer primary key "ct.id" — so a later ContentTypeManager.get_for_id 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.clear_cache exists and why Django’s test runner clears it automatically.)

Watch both "ada"'s per-instance "_perm_cache" staleness trap and ContentTypeManager._cache returning the identical cached object at 0 SQL queries live on "desk/":

Recorded on Django 6.1.3 ch11-auth script
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.contrib.admin — 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.