Adding a custom Prefetch to a cloned queryset mutates the original query

Open
#2,372 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

@IlyaKhalafi is already working on this.

Since Oct 24, 2026.

  • #2373 by @IlyaKhalafi — open

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
35/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Stale
Tech stack
python
Domain
databases

Research direction

The repro imports Prefetch from tortoise.query_utils and calls prefetch_related. Read the prefetch_related implementation and the queryset clone logic. Run the snippet to confirm second_parent leaks into original. Done when original queryset remains unchanged; PR #2373 is open.

Written by the indexing model from the issue text.

Description

Here Child.parent is a foreign key to Parent. On current develop, a queryset clone shares the lists of custom prefetch queries with the original. Adding another Prefetch for the same relation changes both queries.

from tortoise.query_utils import Prefetch

original = Child.all().prefetch_related(
    Prefetch("parent", Parent.all(), to_attr="first_parent")
)
derived = original.prefetch_related(
    Prefetch("parent", Parent.all(), to_attr="second_parent")
)
row = await original.first()

When a child exists, row also has second_parent even though it was only requested on derived. The original queryset should remain unchanged.

Dominant language
Python
Stars
5.6k
Forks
540
Avg merge
4d 10h
Merged PRs (30d)
31

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from tortoise/tortoise-orm

All issues in tortoise/tortoise-orm

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.