Deferring the per-instance related manager and QuerySet in prefetch_related()

Hi all,

I’d like feedback on a prefetch_related() optimisation before opening a ticket.

We run a Django + DRF API with many list endpoints whose serializers read several prefetched to-many relations per row. Profiling them, we found that switching prefetches to Prefetch(..., to_attr=...) made them noticeably faster. The docs recommend to_attr for filtered prefetches because it’s less ambiguous, but don’t mention it’s faster; that would be worth adding.

Changing every reader to use to_attr isn’t always practical, so I aimed for parity with to_attr inside prefetch_related() itself. The patch below closes about half the gap. Most of the rest is on the read side: each obj.books access still builds a new related manager, which to_attr avoids by returning a plain list.

The cost

For a to-many prefetch without to_attr, prefetch_one_level() does this per parent instance:

manager = getattr(obj, to_attr)
if leaf and lookup.queryset is not None:
    qs = manager._apply_rel_filters(lookup.queryset._chain())
else:
    qs = manager.get_queryset()
qs._result_cache = vals
qs._prefetch_done = True
obj._prefetched_objects_cache[cache_name] = qs

That builds a related manager and a filtered QuerySet per instance just to hold vals; to_attr does a single setattr(). For 2,000 authors with prefetch_related("books") (Django 5.2), that’s 4,001 related managers and 2,001 QuerySets, against 1 and 1 with to_attr. In list endpoints serializing many rows with several to-many relations, it’s a large part of the Python time.

Previous tickets:

  • #19264 “prefetch_one_level is slow” was closed as a duplicate of #20577, noting the cached QuerySet “must still behave the same way as the original QuerySet, apart from having its _result_cache already filled”.
  • #20577 deferred applying the filter, and suggested storing results in “a plain list you can name”. to_attr does that, but every reader of the relation has to change.
  • #30842 was also closed as a duplicate of #20577.
  • #26676: the 1.10 regression where to_attr lists ended up in the relation’s cache and broke .filter(). Any change here has to avoid that.

The proposal

Keep a real QuerySet in the cache, but build its query lazily. prefetch_one_level() stores an instance of a subclass of the related manager’s QuerySet class, with no query and the prefetched objects as its result cache. Iteration, len(), bool(), indexing, count() and exists() already read _result_cache, so they never build anything.

When something first needs the query, the _query property creates the related manager and runs manager._apply_rel_filters() as today, then reassigns __class__ to the original QuerySet class, keeping the result cache. M2M and generic relation managers bind to instance values when created, so those are recorded at prefetch time and used for the build in case the pk has since changed. _clone(), __deepcopy__() and __reduce_ex__() build first, so chaining, copying and pickling are unchanged. isinstance(qs, QuerySet) and custom QuerySet classes from Prefetch(queryset=...) still work, and there’s no new API.

The patch is about 100 lines in django/db/models/query.py, plus tests:

Results

Tests: the full suite passes on SQLite (19,907 tests). New prefetch_related tests cover:

  • reads not touching the query;
  • .filter() giving the same SQL as an unprefetched manager (M2M and reverse FK);
  • a custom QuerySet class from Prefetch(queryset=...);
  • remove() clearing the cache;
  • pickling and deepcopy();
  • the #33984 scenario (copying a prefetched instance with pk = None and save()): a QuerySet obtained before the copy stays bound to the original instance, as today.

Benchmark: main (ce285ce0e7), in-memory SQLite, 2,000 authors, 6,000 books, 12,000 book–tag links; prefetch_related("books", "books__tags"), then reading a.books.all() and b.tags.all(). Three alternating runs each:

Build Median Best
main 301–312 ms 232–264 ms
patched 205–212 ms 159–176 ms
to_attr (either build) 118–137 ms 103–122 ms

Of the remaining gap, a little over half is on the read side (building a manager on each obj.books access, see #32980). The rest is at prefetch time: the per-instance QuerySet holders, and the extra garbage collection they cause.

Real-world: an out-of-tree version on Django 5.2 with MySQL cut median response times on several of our DRF list endpoints. For example, a 1,618-row list went from 1,408 ms to 979 ms, with identical output and SQL.

Questions

  1. Is a dynamic QuerySet subclass that swaps its __class__ acceptable in core? An alternative is a cheap QuerySet built without the related manager, with the relation filter applied lazily, extending #20577’s deferred filter to the whole clone.
  2. Until the query is built, type(qs) is QuerySet is False (isinstance() holds, and the name is the same). Is that a compatibility concern?
  3. A custom QuerySet whose __init__ reads self.query would break. Worth guarding against?
  4. New “Cleanup/optimization” ticket, or reopen #20577?

Benchmark scripts

Put models.py in a minlib/ package (with an empty __init__.py) next to bench.py, then run PYTHONPATH=/path/to/django python bench.py.

minlib/models.py
from django.db import models


class Tag(models.Model):
    name = models.CharField(max_length=50)

    class Meta:
        app_label = "minlib"


class Author(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        app_label = "minlib"


class Book(models.Model):
    author = models.ForeignKey(Author, models.CASCADE, related_name="books")
    title = models.CharField(max_length=100)
    tags = models.ManyToManyField(Tag)

    class Meta:
        app_label = "minlib"
bench.py: prefetch benchmark
"""prefetch_related on 2,000 authors / 6,000 books / 12,000 book-tag links. Run with any Django on sys.path."""
import os, statistics, sys, time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import django
from django.conf import settings
settings.configure(INSTALLED_APPS=["minlib"], DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}}, DEFAULT_AUTO_FIELD="django.db.models.AutoField")
django.setup()
from django.db import connection
from django.db.models import Prefetch
from minlib.models import Author, Book, Tag

with connection.schema_editor() as se:
    for m in (Tag, Author, Book):
        se.create_model(m)
N = 2000
tags = Tag.objects.bulk_create(Tag(name=f"t{i}") for i in range(10))
Author.objects.bulk_create(Author(name=f"a{i}") for i in range(N))
books = Book.objects.bulk_create(Book(author_id=i % N + 1, title=f"b{i}") for i in range(N * 3))
Book.tags.through.objects.bulk_create(Book.tags.through(book_id=b.pk, tag_id=tags[(b.pk + k) % 10].pk) for b in books for k in (1, 4))

def run(lookups, read):
    times = []
    for _ in range(11):
        t = time.perf_counter()
        authors = list(Author.objects.prefetch_related(*lookups))
        read(authors)
        times.append((time.perf_counter() - t) * 1000)
    return statistics.median(times), min(times)

def read_plain(authors):
    for a in authors:
        for b in a.books.all():
            list(b.tags.all())

def read_attr(authors):
    for a in authors:
        for b in a.book_list:
            list(b.tag_list)

for label, lookups, read in [
    ("prefetch_related('books', 'books__tags')", ["books", "books__tags"], read_plain),
    ("to_attr", [Prefetch("books", to_attr="book_list"), Prefetch("book_list__tags", to_attr="tag_list")], read_attr),
]:
    med, best = run(lookups, read)
    print(f"{label:<44} median {med:7.1f} ms   best {best:7.1f} ms")
print("django", django.get_version(), django.__file__)

The patch and tests were written with an AI coding assistant; I’ve reviewed and verified the changes and results myself.

Thanks for reading. I’m happy to adjust the approach before writing up a ticket.

Hi, thanks for this–we’re interested in potential performance gains. (Btw, the speed of to_attr is mentioned.)

The proposal is quite complex. I would love to look for smaller, simpler wins first.

Your bench shows a lot of time inside ManyRelatedManager.__init__(), where there are many property lookups that only depend on the relation, not on the specific instance provided to the __init__().

I asked a model to hoist those instance attributes to class attributes, and I got this diff for testing. Under your bench, it makes a 10% speed improvement.

We have an existing ticket for improving the performance of this very location. Would you like to assign it to yourself, verify the soundness of the changes, and report back, possibly with a PR?

Thanks, I was a bit concerned about the likelihood of getting that through as is. I have toned it down and found one more cheap one besides what you pointed out.

1 Like