tortoise / tortoise/tortoise-orm

relation not found - How to use .fetch_related()?

Open
#1,514 3 comments 0 reactions 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
I've setup a ForeignKey field and appropriate model. When fetching the object I can't access the object under the ForeignKey field. Using .fetch_related says relation not found.

To Reproduce

# mymodels.py

from tortoise.models import Model
from tortoise import fields

class Preset(Model):
    name = fields.CharField(max_length=255)
    setting1 = fields.ForeignKeyField('models.Setting1', related_name='preset')
    
    def __str__(self):
        return self.name

class Setting1(Model):
    name = fields.CharField(max_length=255)
    
    def __str__(self):
        return self.name
# setup_data_and_test.py

from mymodels import *
from tortoise import Tortoise, run_async

async def init():
    await Tortoise.init(db_url='sqlite://db.sqlite3',  modules={'models': ['mymodels']})
    await Tortoise.generate_schemas()

async def add_data():
    s1 = await Setting1.create(name="Test-Setting1")
    p1 = await Preset.create(name="Preset1", setting1=s1)

async def done():
    await Tortoise.close_connections()

async def get_data():
    all_presets = await Preset.all()
    for entry in all_presets:
        print('Preset:', entry.name)
    
    await all_presets[0].fetch_related('preset')
    print(all_presets[0].setting1.name)

run_async(init())
run_async(add_data())
run_async(get_data())
run_async(done())

So when I run setup_data_and_test.py I get:

$ setup_data_and_test.py
Preset: Preset1
Traceback (most recent call last):
  File "D:\tortoise_orm_example\setup_data_and_test.py", line 25, in <module>
    run_async(get_data())
  File "C:\Python310\lib\site-packages\tortoise\__init__.py", line 688, in run_async
    loop.run_until_complete(coro)
  File "C:\Python310\lib\asyncio\base_events.py", line 646, in run_until_complete
    return future.result()
  File "D:\tortoise_orm_example\setup_data_and_test.py", line 20, in get_data
    await all_presets[0].fetch_related('preset')
  File "C:\Python310\lib\site-packages\tortoise\models.py", line 994, in fetch_related
    await db.executor_class(model=self.__class__, db=db).fetch_for_list([self], *args)
  File "C:\Python310\lib\site-packages\tortoise\backends\base\executor.py", line 585, in fetch_for_list
    raise OperationalError(
tortoise.exceptions.OperationalError: relation preset for preset not found

Expected behavior
I would expect to access the data of the FK-object. Or am I missing something here? How could I access objects under ForeignKey-fields?

Additional context
tortoise-orm: 0.20.0
OS: Win 10/x64
Py: Python 3.10.6

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

Start with mymodels.py and setup_data_and_test.py, then read tortoise/models.py around fetch_related and tortoise/backends/base/executor.py around the reported error. Reproduce the failure with the shown SQLite setup and verify the declared ForeignKey relation and the name passed to fetch_related. Done means the example can access the related Setting1 object without a relation-not-found error.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sqlite
Domain
backend, databases
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.