tortoise / tortoise/tortoise-orm
Automatically optimize prefetch_relation to use a single query for single-record relations — WAS: .only fails where .values doesn't
Open
Nobody has claimed this yet.
enhancement
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 516
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 9
Description
Describe the bug
.only fails where .values succeeds.
To Reproduce
results = await Mask.all().limit(5).values('name', 'tapeoutprojectname__tapeoutprojectname')
Works
results = await Mask.all().limit(5).only('name', 'tapeoutprojectname__tapeoutprojectname')
Doesn't and results in:
if field in self.annotations:
self._annotations[return_as] = self.annotations[field]
return
field_split = field.split("__")
if field_split[0] in self.model._meta.fetch_fields:
related_table, related_db_field = self._join_table_with_forwarded_fields(
model=self.model,
table=table,
field=field_split[0],
forwarded_fields="__".join(field_split[1:]),
)
self.query._select_field(related_table[related_db_field].as_(return_as))
return
> raise FieldError(f'Unknown field "{field}" for model "{self.model.__name__}"')
E tortoise.exceptions.FieldError: Unknown field "tapeoutprojectname__tapeoutprojectname" for model "Mask"
../playground/tortoise-orm/tortoise/queryset.py:910: FieldError
============================================================================ 1 failed in 1.69s =============================================================================
Expected behavior
I expected mask objects with tapeoutprojectnames.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by reproducing the two Mask queries from the issue and inspect tortoise/queryset.py around line 910, where the nested field raises FieldError. Trace how .values resolves tapeoutprojectname__tapeoutprojectname versus .only, then verify that .only returns Mask objects with the related tapeoutprojectnames and that single-record relations use one query as requested.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend, databases
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100