Article | October 11, 2026

Hunting Down Quadratic Loops in django CMS

How PR #8913 removed quadratic work from django CMS menus, plugins, and page permissions: a permission-heavy menu on a 4,000-page site went from 11.7 seconds to 105 ms.

5 minutes read

Hidden work in django CMS and django-filer

Last week I merged PR #8913 into django CMS core. It touches some of the oldest code in the project: the menu system, the menu modifiers, plugin downcasting and the page-permission check that decides which pages a visitor may see. In a local, uncached benchmark, a permission-heavy menu on a 4,000-page site went from 11.7 seconds to 105 ms.

A few days later the same work landed in django-filer, the file manager that almost every django CMS site runs, through PR #1648 and its follow-up PR #1652. Filer had the same problem in a different place. In django CMS, the hidden cost was usually a list copy. In filer, it was usually a database query. A cold permission check on a deeply nested folder tree went from 693 ms to 0.65 ms. In a real django CMS project with 11,646 files, the duplicate-file finder went from 8.8 seconds to 12 ms.

Almost none of that came from clever algorithms. It came from removing work that Python hides behind innocent-looking syntax. If you take one thing from this post, take this: an O(n) operation inside a loop over n items is O(n²), and Python lets you write O(n) operations that look like O(1). Django goes one step further: it lets you write a database round trip that looks like an attribute read.

The first half of this post covers django CMS: the patterns I found, how to recognize them, when they actually matter, and how to write tests that catch them without a stopwatch. The second half applies the same lens to django-filer, where most of the patterns cost a SQL query instead of a list operation.

The cheat sheet

Looks like What it really does Use instead
sum(lists, []) Copies everything collected so far on every + list(chain.from_iterable(lists))
[a] + recurse(...) in a recursive function Copies each subtree once per ancestor An explicit stack
lst.remove(x) in a loop Scans for x, then shifts every later element Collect, then filter once
x in lst in a loop Scans the list x in some_set
Re-queueing items "until they work" Up to n retries per item Wait until the dependency is ready
obj.children.all() in a recursive function One query per node One query per tree level
perm.folder.id, user == obj.owner Loads a row to read a key you already have perm.folder_id, obj.owner_id
len(qs.filter(...)) in a loop One query per item, loading whole groups One aggregate query
Paginator(list(qs), ...) Loads every row to show one page Paginate the queryset

The first five were in django CMS, the last four in django-filer. Let's go through them.

Part 1: django CMS

1. Copying instead of collecting: sum(lists, [])

create_default_plugins gathered the plugins it created for each placeholder like this:

return sum(starmap(_create_default_plugins, mutable_confs), [])

sum evaluates acc + next_list repeatedly, and each + builds a new list containing everything collected so far. Joining 800 one-element lists copies 1 + 2 + … + 800 = 320,400 elements to produce an 800-element list.

The fix is a one-liner from the standard library:

return list(chain.from_iterable(starmap(_create_default_plugins, mutable_confs)))

The same pattern hid in a worse form in NavigationNode.get_descendants:

return sum(([node] + node.get_descendants() for node in self.children), [])

Because it's recursive, every subtree is copied once at its own level, then again at its parent's level, and again at every ancestor's level. Cost grows with depth × size. On a deep tree, it also runs into Python's recursion limit.

chain alone doesn't fix recursion, so here the answer is an explicit stack:

descendants = []
pending = list(reversed(self.children))
while pending:
    node = pending.pop()
    descendants.append(node)
    pending.extend(reversed(node.children))
return descendants

Reversing the children before pushing them keeps the original preorder, so callers see exactly the same list as before. Each node is touched once, and there is no recursion to overflow. get_ancestors, flatten and the nav-extender cut_levels got the same treatment.

How to spot it: any + on lists inside a loop or a recursive return value.

2. Removing while iterating: a performance bug that was also a correctness bug

The submenu tag trimmed invisible children like this:

for child in node.children:
    if child.visible:
        cut_after(child, levels - 1)
    else:
        node.children.remove(child)

list.remove has to find the element and then shift every element after it one slot to the left. Do that for many children and the loop becomes quadratic.

It's also wrong. A list iterator is just an index that moves forward. Take children [A, B, C] where A and B are invisible:

Step Iterator index List Action
1 0 → A [A, B, C] remove A → [B, C]
2 1 → C [B, C] C is visible, keep it
done [B, C] B was never looked at

Every second consecutive invisible child stayed in the menu. The fix filters first, then recurses:

node.children[:] = [child for child in node.children if child.visible]
for child in node.children:
    cut_after(child, levels - 1)

Note the slice assignment, node.children[:] = ..., rather than node.children = .... Other code may hold a reference to the same list object. Slice assignment replaces its contents in place, so everyone sees the change. Rebinding the name would silently leave them with the old list.

Where nodes had to be removed from several parents, as in AuthVisibility and the menu tag's cut_levels, the PR adds a small helper that collects every node to remove and filters each parent's children exactly once:

def detach_from_parents(nodes):
    removed = set()
    parents = {}
    for node in nodes:
        removed.add(id(node))
        if node.parent:
            parents[id(node.parent)] = node.parent
    for parent in parents.values():
        parent.children[:] = [c for c in parent.children if id(c) not in removed]

The old AuthVisibility code was a good example of hidden double work: node in node.parent.children scans the list, then node.parent.children.remove(node) scans it again.

How to spot it: .remove(), .pop(0) or .insert(0, …) inside a loop. The fix is always the same: decide first, then rebuild once.

3. Membership tests on a list

downcast_plugins and get_bound_plugins collected plugin ids into a list and then, for every plugin, checked whether its parent was among them:

plugin_ids = []
for plugin in plugins:
    plugin_ids.append(plugin.pk)
...
for plugin in plugins:
    parent_not_available = not plugin.parent_id or plugin.parent_id not in plugin_ids

The not in is easy to miss: it's buried in a boolean expression, not in a loop of its own. But it's a linear scan, run once per plugin. The fix was to collect the ids in a set instead of a list:

plugin_ids = set()  # A set: it is checked for every plugin
...
plugin_ids.add(plugin.pk)

Why does that help? Lists and sets answer x in ... in completely different ways. A list stores its items in order and knows nothing about their values, so x in lst compares x with each item until it finds a match or reaches the end. A missing value, like a parent id that isn't there, is the worst case, because every item gets checked.

Sets (and dict keys) are built for exactly this question. A set is a hash table: when an item is added, Python computes hash(item) and uses it to pick a slot in an internal array. x in some_set computes hash(x), jumps straight to that slot, and compares only the few items stored there, usually just one. The cost doesn't depend on how many items the set holds, so a lookup in a set of 16,000 plugin ids costs about the same as in a set of 10.

There are two trade-offs: items must be hashable (ints, strings and tuples are), and sets don't keep insertion order. Neither mattered here. If you need both ordering and fast lookups, keep the list for iterating and build a set alongside it for in checks.

How to spot it: any in whose right-hand side is a list built earlier in the function.

4. The main course: page permissions

This was the case that turned 105 ms into 11.7 seconds, because here the repeated work reached the database.

To decide whether a visitor may see a page, django CMS checks view restrictions. A restriction on a page can also apply to its children or descendants. The old code did the obvious thing. For every page in the menu, it looped over every restriction and asked whether that restriction covers the page:

for perm in restrictions:
    if perm.get_page_permission_tuple().contains(page.path):
        ...

That alone is pages × restrictions. Worse, get_page_permission_tuple() reads perm.page.path, and perm.page is a lazy foreign key. The old code pre-filled that cache only for a page's own restriction. Every restriction inherited from an ancestor triggered a fresh query. A 1,602-page menu with restrictions on shared ancestors issued 1,617 SQL queries in one render.

The fix uses the structure of the data to limit which rules can possibly apply.

django CMS stores the page tree as a materialized path: each page's path is its parent's path plus a fixed-width step. A page's ancestors are therefore exactly the pages whose paths are prefixes of its own path. So instead of asking "which of all restrictions covers this page?", we can ask "are there restrictions on any of my depth prefixes?":

for end in range(Page.steplen, len(page.path) + 1, Page.steplen):
    perm_path = page.path[:end]
    for scope, granted in restrictions_by_path.get(perm_path, {}).items():
        if not scope.contains(page.path):
            continue
        if granted:
            return True
        restricted = True

That's one dictionary lookup per tree level instead of one check per restriction.

Two more ideas make it work:

  • Use the data you already have. The paths come from the pages that are already loaded for the menu (page_paths = {pc.page.pk: pc.page.path for pc in page_contents}), so perm.page is never touched and the N+1 queries disappear.
  • Decide once per rule, not once per page. Whether the current user is granted a given scope doesn't depend on which descendant is asking. The code resolves that once while it builds the index:

python grants[scope] = grants.get(scope, False) or ( is_auth_user and (perm.user_id == user_id or perm.group_id in user_groups) )

The per-page loop only reads a boolean.

The query count dropped from 1,617 to 18, and it stayed at 18 for 4,002 pages.

The general lesson goes beyond django CMS. When you're matching many items against many rules, look for a key that tells you which rules can apply: a prefix, a parent, a type, a date bucket. Index the rules by it, and the cross product disappears.

5. Building the menu tree without retries

Menu nodes from custom menus and apphooks can arrive in any order. A child may come before its parent, or point to a parent that doesn't exist. The old builder handled this with a queue. It popped a node, and if the node's parent hadn't been seen yet, it appended the node to the back and tried again later. To avoid looping forever, a counter on each node stopped retrying after len(nodes) attempts.

That's correct, but a node whose parent never appears gets retried up to n times. A tree that arrives in reverse order needs one full pass per level.

The new builder waits instead of retrying. A node whose parent isn't linked yet is parked in a dictionary keyed by (namespace, parent_id). When the parent is linked, its waiting children are released.

The subtle part is order. Menus are rendered in the order their nodes end up in, and existing sites depend on that order. The old queue processed nodes in rounds, so the new code reproduces those rounds exactly with a heap of (round, position, node):

for child_position, child in waiting.pop((node.namespace, node.id), ()):
    child_round = round_number if child_position > position else round_number + 1
    heapq.heappush(visits, (child_round, child_position, child))

A released child that sits after its parent in the input would still have been reached in the current round. One that sits before it would have waited for the next round. Every node is visited at most twice, and orphans are simply never released.

When you rewrite legacy code, don't stop at "it produces the same tree". Ask what callers can observe, here the ordering, and keep it.

When does any of this matter?

Here are request-level timings, measured locally: median full-response time, SQLite, one WSGI worker, Python 3.14, Django 5.2, no menu cache.

Workload Before → After Speedup SQL queries
Unrestricted menu (control), 1,602 pages 106 → 107 ms 0.99× 17 → 17
Shared ancestor restrictions, 1,602 pages 2,016 → 45 ms 45× 1,617 → 18
Shared ancestor restrictions, 4,002 pages 11,729 → 105 ms 112× 4,017 → 18
16,000 plugins / 80 placeholders 1,008 → 497 ms 2.0× 19 → 19
4,000 reverse-ordered custom-menu nodes 269 → 266 ms 1.01× 17 → 17

The last row deserves a closer look. On that workload, the tree builder now does about 23× less work (81,796 → 3,592 counted operations at the larger size), yet the request is only 1% faster. Comparing a few thousand integers in memory is cheap. Rendering templates and talking to the database dominate.

The pattern shows up across the table:

  • Quadratic in-memory work hurts only once n gets large, as with 16,000 plugins.
  • Quadratic work that touches I/O hurts almost immediately. The permission check was a quadratic loop with a query inside it.

So profile first. Fix the loop that is slow in practice, and treat the others as cheap insurance. The control row and the identical HTML output (every benchmark response hashed the same before and after) are what tell you a change is safe, not just fast.

Testing growth without a stopwatch

Timing tests are flaky: CI machines differ, and noise swamps small inputs. Fabian pointed this out in review, and it led to the most reusable idea in the PR. Count operations instead of measuring time, and assert on how the count grows.

The tests in cms/tests/test_scaling.py use instrumented types that increment a counter whenever they are compared, hashed, iterated or concatenated:

class CountingId(int):
    def __eq__(self, other):
        Work.count += 1
        return int(self) == int(other)

    def __hash__(self):
        Work.count += 1
        return int.__hash__(self)


class CountingList(list):
    def __add__(self, other):
        Work.count += len(self) + len(other)   # every copied element
        return CountingList(super().__add__(other))
    # __iter__, __reversed__ and __radd__ count the same way

Then each test runs the code on n and 4n items and compares:

def assertLinearCount(self, run, n):
    Work.count = 0
    run(n)
    small = Work.count

    Work.count = 0
    run(4 * n)
    large = Work.count

    self.assertLess(large, 8 * max(small, 1), f"work grew from {small} to {large}")

Linear code grows about 4×, quadratic code about 16×, and the threshold of 8× sits safely between them. The result is deterministic, fast, and independent of the machine. All 29 scaling tests fail on the pre-fix code and pass afterwards. For example, removing nodes that don't belong to any nav extender went from 40,000 → 640,000 operations (16×) to 400 → 1,600 (4×).

Two related tricks were worth using too:

  • Recursion-limit tests. Build a chain of sys.getrecursionlimit() + 1 nodes and call get_ancestors and flatten on it. It's cheap, and it pins down the "no recursion" property for good.
  • Differential testing. I generated 2,000 random menu trees and checked that the old and new code produce identical flatten order, visibility and tree mutations. When the rewrite must not change behavior, comparing it with the old code on random input finds the edge cases that hand-written tests miss.

The full django CMS suite (1,916 tests) is green, and the change has been backported to the 5.0.x and 5.1.x release branches, so you don't need to wait for a major release to benefit.

Part 2: django-filer

Filer stores folders as an adjacency list: each Folder has a parent foreign key and nothing else. There is no materialized path and no nested set. That matters, because the trick from section 4, finding ancestors by path prefix, isn't available. Every question about a subtree ("which folders are below this one?", "may this user edit everything I'm about to move?") has to be answered by walking it.

Most of the old code walked it the way you'd write it on a whiteboard: recursively, through the ORM. Each step of that recursion is a query.

6. Recursion through the ORM

Here is the old Folder.get_descendants_ids:

def get_descendants_ids(self):
    desc = []
    for child in self.children.all():
        desc.append(child.id)
        desc.extend(child.get_descendants_ids())
    return desc

It looks harmless, and in one sense it is: every folder is visited once, so the algorithm is linear. But it is linear in queries. self.children.all() is a SELECT, and it runs once per folder. A root with 200 subfolders, each with one subfolder of its own, takes 401 queries to answer "what's below the root?". On SQLite in the same process, that costs 52 ms. On a networked database, each of those queries also pays a round trip.

The same shape was in the move, copy and delete permission checks, the clipboard and public/private actions, the copy/move/resize confirmation lists, the delete confirmation and the destination picker. For example:

def check_folder_edit_permissions(request, folders):
    for f in folders:
        if not f.has_edit_permission(request):
            raise PermissionDenied
        check_files_edit_permissions(request, f.files)
        check_folder_edit_permissions(request, f.children.all())

Two queries per folder, recursively, before the admin even shows the confirmation page.

The fix is to walk the tree breadth-first, one level per query. All children of every folder on the current level come from a single parent_id IN (...) query, so the query count grows with the tree's depth, not with its size. The PR consolidates this into one small walker that every caller shares:

def walk_tree_levels(roots, children):
    """Yield keyed levels once, including roots, even with overlaps or cycles."""
    level = dict(roots)
    seen = set(level)
    while level:
        yield level
        level = {pk: obj for pk, obj in children(level) if pk not in seen}
        seen.update(level)

Three details make it safe to use everywhere:

  • The seen set. Admins can select a folder and one of its subfolders in the same action. The old recursion visited the overlap twice. The walker visits every folder once. As a side effect, a corrupted parent cycle now ends the walk instead of recursing until Python raises RecursionError.
  • Bounded IN lists. children(level) fetches through filter_in_batches, which splits large levels to stay under the backend's parameter limit. More on that in section 11.
  • Order. Callers depended on the old recursion's depth-first, name-ordered output. Breadth-first loading doesn't produce that order, so get_descendants_ids fetches (id, parent_id) rows sorted by name and rebuilds the preorder in memory:

```python children = {} for pk, parent_id in _descendant_rows([self.pk]): children.setdefault(parent_id, []).append(pk)

ordered = [] pending = list(reversed(children.get(self.pk, []))) while pending: pk = pending.pop() ordered.append(pk) pending.extend(reversed(children.get(pk, []))) return ordered ```

That's the explicit stack from section 1, now fed by three queries instead of 401. The lesson from section 5 applies again: load the data the efficient way, then restore the order callers can observe.

Why not a recursive CTE? WITH RECURSIVE would answer the whole question in one query, and SQLite, PostgreSQL and MySQL 8 all support it. But the Django ORM can't express it, so it means raw SQL and per-backend testing. Level batching is portable and removes nearly all of the cost on realistic trees, which tend to be wide rather than deep. The code leaves a TODO for SQL-side traversal in folder-limited search, where splitting IN lists bounds each query but not the total number of parameters.

How to spot it: a related manager (.children.all(), .files, .all_files) inside a recursive function or nested loop.

7. Permissions: the same lesson as core, in a different shape

Filer decides folder access by computing, per user, the set of folder ids they may read, edit or add to. The old code:

for perm in perms:
    p = getattr(perm, attr)
    ...
    folder_id = perm.folder.id
    ...
    if perm.type in [FolderPermission.ALL, FolderPermission.CHILDREN]:
        if p == FolderPermission.ALLOW:
            allow_list.update(perm.folder.get_descendants_ids())
        else:
            deny_list.update(perm.folder.get_descendants_ids())

Three costs are stacked here:

  1. perm.folder.id loads the folder row to read a value that already sits on the permission row as perm.folder_id. That's an N+1 over grants.
  2. get_descendants_ids() is the recursion from section 6: one query per folder below each grant.
  3. Overlapping grants repeat the walk. Real installations stack grants: a group grant on the root, a user grant on /clients/acme, a deny on /clients/acme/contracts. Each grant walks its own subtree, so nested grants walk the same folders again and again. With a grant at every level of a chain of depth d, the walks cost d + (d − 1) + … + 1 queries. At 100 levels, that's 5,151 queries for a single cold permission check.

The new code reads plain columns and walks every subtree together:

for folder_id, scope, permission in self.filter(q).values_list('folder_id', 'type', attr):
    if permission is None:
        continue

    grant = FolderPermission.ALLOW if permission == FolderPermission.ALLOW else FolderPermission.DENY
    if folder_id is None:
        global_grants.add(grant)
        continue

    id_lists[grant].add(folder_id)
    if scope in (FolderPermission.ALL, FolderPermission.CHILDREN):
        subtree_roots[grant].add(folder_id)

# A global denial overrides every grant without reading any folders.
if FolderPermission.DENY in global_grants:
    ...

for grant, roots in subtree_roots.items():
    ...
    id_lists[grant].update(subtree_ids(roots))
  • values_list never builds a FolderPermission instance, so perm.folder can't be touched by accident.
  • Roots are collected first, then walked together. The walker's seen set means each folder is read at most once per allow/deny set, however much the grants overlap. It's the "decide once per rule" idea from section 4, applied to a tree without paths.
  • A global deny wins over everything, so the old code's work of loading every folder id only to subtract it is skipped.

At 100 levels of overlapping grants, a cold check went from 5,151 queries and 693 ms to 2 queries and 0.65 ms. In the live django CMS project, a cold check on 50 nested levels went from 4,060 to 89 queries and from 619 to 55 ms.

There are two limits.

First, level batching is bounded by depth. A single grant at the root of a 100-level chain still costs 101 queries, one per level, and only gets about 1.5× faster (14.3 → 9.7 ms). With an adjacency list and no recursive SQL, depth sets a minimum number of queries.

Second, one change was reverted on purpose. Filer caches each user's id list, and the cache treats an empty result as a miss, so users with no grants recompute on every check. The PR's first commit made empty results cache hits. That was faster, but it was wrong: adding a user to a group or running a bulk update(everybody=True) doesn't invalidate the cache, so a newly granted user would stay locked out until the cache expired. I reverted it, and the benchmarks keep the cost visible: repeated empty checks are 16–22% slower in this run. Doing this properly needs versioned, per-user cache invalidation, which deserves its own PR. A faster permission check that gives the wrong answer isn't an improvement.

8. A query that looks like a filter: duplicate detection

def find_all_duplicates(self):
    r = {}
    for file_obj in self.all():
        if file_obj.sha1:
            q = self.filter(sha1=file_obj.sha1)
            if len(q) > 1:
                r[file_obj.sha1] = q
    return r

len(q) evaluates the queryset: it runs a query and loads every file with that digest. It runs once per file, including every unique one. For a group of k identical files, that's k queries that each load k rows, k² rows in total, and the same dictionary key is overwritten k times. In the live project, the duplicate manager issued 11,807 queries and took 8.8 seconds.

The question "which digests occur more than once?" is an aggregate. Let the database answer it:

digests = (
    self.exclude(sha1='').order_by().values('sha1')
    .annotate(total=Count('pk')).filter(total__gt=1)
    .values_list('sha1', flat=True)
)
groups = {}
for file_obj in self.filter(sha1__in=digests).order_by('sha1', 'pk'):
    groups.setdefault(file_obj.sha1, []).append(file_obj)

That compiles to a GROUP BY sha1 HAVING COUNT(*) > 1 subquery inside a single SELECT. Two details are easy to get wrong:

  • .order_by() before .values(). Django adds ordering columns to GROUP BY. Any ordering on the queryset would silently split groups, so the code clears it.
  • exclude(sha1=''). The old loop skipped files without a digest with if file_obj.sha1. The SQL has to do the same, or every file without a digest would fall into one large "duplicate" group.

The return type was the harder part. Callers expect a dict of evaluated querysets that they can still filter or delete. The new code builds self.filter(sha1=sha1) for each group and seeds its result cache with the rows it already loaded. That relies on Django's private _result_cache. I accepted that trade-off to keep the public API unchanged, and tests pin it.

A group of 400 identical files went from 401 queries and 1,073 ms to 1 query and 3 ms. Through HTTP in the live project, the duplicate manager went from 8,761 ms to 11.6 ms and from 11,807 queries to 5.

How to spot it: len(qs), qs.count(), qs.exists() or bool(qs) inside a loop. If the loop computes a property of groups, it's an aggregate.

9. Paginate before you materialize

The directory listing built its page like this:

items = list(itertools.chain(folder_qs, file_qs))

and then handed items to Django's Paginator. Paginator is lazy with querysets: it calls count() and slices. With a list, every row has already been loaded. Opening a folder with 10,000 files built 10,000 polymorphic model instances to render 100 of them.

The PR replaces the list with FolderItems, a small sequence over the two querysets. Its len() is two COUNT queries. Its slices are translated into LIMIT/OFFSET on whichever queryset, or both, the page covers.

Paginating in SQL has a requirement that's easy to miss: ordering must be total. With ORDER BY name and two files called logo.png, the database may return the tie in either order, and it doesn't have to be consistent between the query for page 1 and the query for page 2. A row can then show up on both pages or on neither. Every listing now ends its ordering with pk:

# Break ties on pk so LIMIT/OFFSET pages never overlap or skip items.
file_qs = file_qs.order_by(*order_by, 'pk')

Each folder row also showed its subfolder and file counts, at two queries per folder. They're now annotations:

children = Folder.objects.filter(parent_id=OuterRef('pk')).order_by().values('parent_id')
files = File.objects.filter(folder_id=OuterRef('pk')).order_by().values('folder_id')
# Separate aggregates avoid multiplying counts by joining both relations.
return queryset.annotate(
    _children_count_cache=Coalesce(
        Subquery(children.annotate(total=Count('pk')).values('total')), 0,
    ),
    _file_count_cache=Coalesce(
        Subquery(files.annotate(total=Count('pk')).values('total')), 0,
    ),
)

Why not annotate(Count('children'), Count('all_files'))? Two JOINs in one query multiply. A folder with 3 subfolders and 4 files produces 12 joined rows, so both counts come out as 12. distinct=True corrects the numbers but still builds the cross product. Correlated subqueries keep each count independent.

Listing a 10,000-file folder went from 370 ms to 38 ms in the benchmark harness and from 192 ms to 37 ms in the live project. Counts for 100 folders went from 204 queries to 5. The small case got slightly worse: a 100-file folder costs one extra COUNT and was about 1 ms slower (34.3 → 35.6 ms). I'll accept that in exchange for a listing whose cost no longer depends on folder size.

10. Django has no identity map

In SQLAlchemy, loading the same row twice in one session returns the same object. Django doesn't do that. file.folder lazily loads a new Folder instance even if that exact folder is sitting in a dictionary two lines above. This matters in filer for two reasons: folder labels walk the parent chain (pretty_logical_path), and permission checks cache their results on the instance. Every fresh copy repeats both.

So the walkers connect relations by hand:

for file_obj in filter_in_batches(File.objects.all(), 'folder_id', level):
    # Reuse the loaded folder and its permission cache.
    file_obj.folder = level[file_obj.folder_id]

Assigning an instance to a foreign key fills Django's relation cache, so file_obj.folder.parent.parent walks objects in memory instead of issuing queries. attach_ancestors does the same upward for the pick-folder popup, loading one ancestor level per query. For the delete confirmation, the patched admin collector got a small _share_source hook that calls field.set_cached_value(child, source), so each collected child points at the parent instance the collector already holds.

The smallest change in the PR shows the same idea:

# Before
elif user == self.owner:
# After
elif self.owner_id is not None and self.owner_id == user.pk:

Model equality compares primary keys, so self.owner loaded a whole user row only to compare a value that was already on the file. The first version of the fix was self.owner_id == user.pk, and an automated review caught the problem: an unsaved user has pk=None, an ownerless file has owner_id=None, and None == None granted ownership. Django's model __eq__ treats unsaved instances as unequal unless they're the same object. A raw key comparison doesn't. When you replace an object comparison with a key comparison, check what happens with NULL.

How to spot it: obj.fk.id or obj.fk == other where obj.fk_id would do, and a foreign key read inside a loop over objects whose related rows you've already loaded.

11. Bound everything

Batching fixes N+1, but it introduces a new failure: unbounded IN lists. Django reports a limit of 999 query parameters for SQLite, and Oracle rejects IN lists longer than 1,000 elements. PostgreSQL and MySQL report no limit, but a 50,000-element IN list is still a very large statement to parse and plan. The helper reads the backend's limit and caps it anyway:

# Bound IN lists even when the backend declares no parameter limit.
QUERY_BATCH_SIZE = 1000

def batched_querysets(queryset, field, ids):
    ids = list(ids)
    max_params = connections[queryset.db].features.max_query_params
    batch_size = min(QUERY_BATCH_SIZE, max_params or QUERY_BATCH_SIZE)
    for offset in range(0, len(ids), batch_size):
        yield queryset.filter(**{f'{field}__in': ids[offset:offset + batch_size]})

Deletion had a quieter version of the same problem: it loaded every file in the selected subtrees at once. It now reads them with keyset pagination:

rows = queryset if last is None else queryset.filter(pk__gt=last)
chunk = list(rows[:size])

OFFSET pagination breaks if you delete the rows you just read, because every later row shifts forward and gets skipped. Filtering on pk > last doesn't shift. Memory stays bounded however many files a folder holds, and each file still goes through delete(), so storage cleanup and subclass hooks keep working.

filer_check --missing used to iterate File.objects.all(), which keeps the entire table in the queryset's result cache. It now uses .iterator(), and it only deletes or reports missing files after the scan finishes, so nothing is written to the table while a cursor over it is still open.

12. Read slowly, and you find bugs

As with the menu code in section 2, reading old code closely enough to make it faster also turned up bugs:

  • On Django 5.1 and later, the delete action logged files_queryset twice instead of logging the folders. Folder deletions were never written to the admin log.
  • In thumbnail view, the pick-folder popup read subfolder.quoted_logical_path, an attribute that no longer exists. Django templates silently render a missing attribute as an empty string, so the widget received an empty label. Setting string_if_invalid in your test settings makes this kind of bug visible.
  • Selecting a file, its folder and a subfolder in one "make public" action raised FileNotFoundError on master. Each file is now updated exactly once.
  • Folder-picker path labels were wrong. In the live benchmark, the only output differences between the old and new code are 100 corrected labels.

None of these showed up as errors in normal use. They were found by comparing outputs before and after the change.

The filer numbers

These were measured in a real django CMS project with Picture and File plugins, real media, CSRF-protected HTTP requests and a restricted user. The fixture has 11,646 files in 459 folders. Each scenario used 3 warmups and 15 timed requests per revision. Setup: SQLite on disk, Python 3.12, Django 5.2, django CMS 5.1, Apple M3 Max.

Scenario Before → After Speedup SQL queries
CMS page (control) 4.11 → 4.01 ms 1.03× 18 → 18
List 100 files 34.33 → 35.55 ms 0.97× 9 → 10
List 10,000 files 192.30 → 37.40 ms 5.1× 18 → 10
Search 10,000 files 183.91 → 40.32 ms 4.6× 18 → 10
Folder-limited search, 400 files 96.79 → 39.03 ms 2.5× 410 → 13
Cold permissions, 50 levels 619.09 → 55.42 ms 11× 4,060 → 89
Move preview, 400 files 406.39 → 46.17 ms 8.8× 2,532 → 65
Resize preview, 400 files 252.05 → 19.62 ms 12.8× 1,652 → 15
Delete preview, 400 files 205.46 → 67.51 ms 3.0× 1,047 → 32
Duplicate manager 8,761 → 11.60 ms 755× 11,807 → 5

The table follows the same pattern as the django CMS one. Whenever the old code put a query inside a loop, the speedup is large. The control row, which doesn't touch the changed code, doesn't move. The small listing got slightly slower and I've left it in the table. Selected IDs matched in all 14 scenarios, and 13 of the 14 normalized response bodies were identical. The 14th differs only by the corrected folder-picker labels.

The synthetic tree benchmarks (docs/benchmarks/tree_scaling.py in the repository) isolate the walks. They ran in three fresh processes per revision, with alternating order, on Python 3.12, 3.14, Django 5.2 and 6.0. All 37 workload outputs matched between revisions. The timings below are from Python 3.12 with Django 5.2. Query counts were the same in every environment.

Workload, 200-folder-wide tree Before → After SQL queries
Descendant IDs of root 52.28 → 1.08 ms 401 → 3
Folder edit permission check 177.37 → 16.22 ms 1,208 → 13
Copy/move destination choices 175.79 → 18.94 ms 1,211 → 15
Copy/move confirmation listing 135.88 → 23.67 ms 804 → 8
Rendered delete confirmation 191.28 → 63.05 ms 1,023 → 27

Testing: count queries, not milliseconds

The django CMS tests counted Python operations. In filer, the expensive operation is a query, so the tests count queries. The idea is the same: assert on how the count grows, not on its absolute value.

assertNumQueries(13) is the usual Django tool, but it pins one number, so it breaks whenever someone adds a harmless query and says nothing about scaling. The filer tests build two trees that differ only in width and require the same query count for both:

SMALL_WIDTH = 2
LARGE_WIDTH = 16

def count_queries(func):
    with CaptureQueriesContext(connection) as queries:
        result = func()
    return result, len(queries)


def test_descendant_queries_follow_depth(self):
    counts = {}
    for width in (SMALL_WIDTH, LARGE_WIDTH):
        root, expected = build_tree(f'tree {width}', width)
        descendants, counts[width] = count_queries(root.get_descendants_ids)
        self.assertEqual(set(descendants), expected)

    # Width must not add queries; only depth may.
    self.assertEqual(counts[SMALL_WIDTH], counts[LARGE_WIDTH])

The old code issues 5 queries at width 2 and 33 at width 16. The new code issues the same number at both. That's the whole contract in one assertion, and it doesn't depend on the machine.

Memory got the same treatment. The filer_check test counts live File instances while scanning 2,500 and then 5,000 rows. It increments on post_init, decrements through weakref.finalize, and records the peak. Both sizes exceed Django's 2,000-row iterator chunk, so the test can require peak(5000) <= peak(2500). The old scan held every row. The new one stays within one chunk.

Every speed fix also has a behavior test that passes on both revisions: exact permission results, deep denials, owner bypasses, labels, ordering, enabled flags and rendered confirmation trees. A scaling test that fails before the change and passes after it shows the fix works. A behavior test that passes on both shows nothing else changed. You need both kinds. In filer, reverting any single fix makes its test fail, and the full suite passes on Django 4.2 through 6.x, both with the default image model and with a swapped one.

Checklist

When you review code that runs per request over a collection of unknown size, look for:

Python

  • sum(..., []), or + on lists in a loop or a recursive return
  • .remove(), .pop(0), .insert(0, …) or .index() inside a loop
  • in against a list that was built earlier in the function
  • modifying a list while iterating over it (a performance smell and a correctness bug)
  • a loop over "all rules" for each item, when a key such as a path prefix, parent or type could narrow the rules down
  • "retry until it works" loops with a safety counter

Django ORM

  • a foreign-key attribute accessed inside a loop (N+1 queries)
  • a related manager such as .children.all() inside a recursive function
  • obj.fk.id or user == obj.owner where obj.fk_id would do, plus a NULL check
  • len(qs), qs.count() or qs.exists() inside a loop: often an aggregate in disguise
  • list(qs) or chain(qs1, qs2) before pagination
  • LIMIT/OFFSET over an ordering that isn't total
  • two Count()s over different joins in the same query
  • IN lists built from data with no upper bound
  • for obj in Model.objects.all() over a whole table, and writes while that cursor is open

Then ask two questions: how large can this get, and does the inner work touch I/O? If the answer to the second is yes, fix it now. In Django, "touches I/O" includes any attribute that might be a relation.

The django CMS change is on master and backported to the 5.0.x and 5.1.x branches. The filer changes are on master.

Article

Hunting Down Quadratic Loops in django CMS

How PR #8913 removed quadratic work from django CMS menus, plugins, and page permissions: a permission-heavy menu on a 4,000-page site went from 11.7 seconds to 105 ms.

Article

One operation, three interfaces: a service architecture for django CMS

How shared content operations could support editors, REST integrations, and AI tools.

Release

django CMS 5.1.3 and 5.0.13 released

We’re pleased to announce the release of django CMS 5.1.3 and django CMS 5.0.13. Both are maintenance releases focused on fixes and improved robustness.