Prefetch with to_attr leaves the attribute missing when all forward relations are null

Open
#2,374 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.

  • #2375 by @IlyaKhalafi — open

Assessment

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

Research direction

The repro in the issue shows a nullable FK prefetched with Prefetch(..., to_attr=...) raising AttributeError instead of setting the attribute to None when all keys are null. Start in tortoise/query_utils.py and the prefetch population code in fields/relational or the queryset prefetch path, where to_attr results are assigned. Look for the branch handling empty/null-only relation groups. Done means the repro returns None; a linked pull request (#2375) already exists, so check it before starting.

Written by the indexing model from the issue text.

Description

Here Child.parent is a nullable foreign key to Parent. The same behavior occurs with nullable one-to-one fields. On current develop, prefetching the relation with to_attr leaves the requested attribute missing when every related key is null.

from tortoise.query_utils import Prefetch

child = await Child.create(parent=None)
row = await Child.filter(pk=child.pk).prefetch_related(
    Prefetch("parent", Parent.all(), to_attr="cached_parent")
).get()
print(row.cached_parent)

The last line raises AttributeError. It should return None, consistent with prefetching a mixed group that includes a non-null relation.

Dominant language
Python
Stars
5.6k
Forks
540
Avg merge
3d 22h
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.