tortoise / tortoise/tortoise-orm

To relations to the same model lead to unexpected behavior

Open
#753 0 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

To relations to the same model lead to unexpected behavior

from tortoise import fields, run_async, Tortoise
from tortoise.fields import ManyToManyRelation, ManyToManyField
from tortoise.models import Model


class MyModel(Model):
    id = fields.IntField(pk=True)
    first: ManyToManyRelation["Property"]
    second: ManyToManyRelation["Property"]


class Property(Model):
    id = fields.IntField(pk=True)

    models_first: ManyToManyRelation["MyModel"] = ManyToManyField("models.MyModel", related_name="first")
    models_second: ManyToManyRelation["MyModel"] = ManyToManyField("models.MyModel", related_name="second")


async def run():

    await Tortoise.init({
            "connections": {
                "default_connection": {"engine": "tortoise.backends.sqlite", "credentials": {"file_path": ':memory:'},},
            },
            "apps": {"models": {"models": ['__main__'], "default_connection": "default_connection"},},
        })

    # Generate the schema
    await Tortoise.generate_schemas()

    m = await MyModel.create(id=1)
    p1 = await Property.create(id=1)
    p2 = await Property.create(id=2)

    await m.first.add(p1)
    await m.second.add(p2)

    print(await m.first.all())  # [<Property: 1>, <Property: 2>] instead of [<Property: 1>]

run_async(run())

Expected behavior
[<Property: 1>] instead of [<Property: 1>, <Property: 2>]

Additional context
The problem is that without an additional through argument both relations use the same table.

Imho the most elegant way to fix this would be to specify the relations from both models:

class MyModel(Model):
    id = fields.IntField(pk=True)
    first = ManyToManyField("model.Property", related_name='models_first')
    second = ManyToManyField("model.Property", related_name='models_second')

class Property(Model):
    id = fields.IntField(pk=True)

    models_first = ManyToManyField("models.MyModel", related_name="first")
    models_second = ManyToManyField("models.MyModel", related_name="second")

That way the related_name could be omitted if it is only one relation

class MyModel(Model):
    id = fields.IntField(pk=True)
    first = ManyToManyField("model.Property")


class Property(Model):
    id = fields.IntField(pk=True)
    models_first = ManyToManyField("models.MyModel")

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 the supplied Python reproduction, focusing on ManyToManyField, Tortoise.generate_schemas(), and the m.first.all() and m.second.add() calls. Trace how the two relations choose their through tables, then verify that each relation returns only its own linked Property records and add regression coverage for the example behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, sqlite
Domain
databases
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.