tortoise / tortoise/tortoise-orm

Nested select_related raises KeyError inside _init_from_db

Open
#1,396 2 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Python
Stars
5.6k
Forks
516
Avg merge
2d 21h
Merged PRs (30d)
9

Description

Describe the bug
When using nested select_related of form:
'modelA__modelB'
I'm getting a KeyError when ORM tries to assign values to modelB.

An issue arises since kwargs values passed to _init_from_db function getting sliced version of model attribute's name, for example, instead of passing 'city_obj' attribute, 'city_ob' is being passed to kwargs, same way instead of attribute 'building', 'buildin' is being passed etc.

Actual error:

File "/usr/local/lib/python3.9/site-packages/tortoise/queryset.py", line 1008, in _execute
instance_list = await self._db.executor_class(
File "/usr/local/lib/python3.9/site-packages/tortoise/backends/base/executor.py", line 155, in execute_select
obj = model._init_from_db(
File "/usr/local/lib/python3.9/site-packages/tortoise/models.py", line 747, in _init_from_db
setattr(self, key, meta.fields_map[key].to_python_value(value))
KeyError: 'buildin'

ORM version:
tortoise-orm==0.19.3

Contributor guide

Open the contributing guide

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.

Research direction

Reproduce the nested select_related case described in the issue using tortoise-orm 0.19.3, then inspect tortoise/queryset.py around _execute and tortoise/models.py around _init_from_db. Trace how relation field names are passed into _init_from_db. Done means the modelB assignment no longer raises the reported KeyError for names such as “buildin” and “city_ob”.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.