tortoise / tortoise/tortoise-orm
[help needed] Filter for list of relations does not work
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 5.6k
- Forks
- 516
- Avg merge
- 2d 21h
- Merged PRs (30d)
- 9
Description
I am trying to find an model that has all relations from the filter query.
It can have more relations, but it can't have less.
Unfortunately it seems the Q relations do not work here.
How would I express id in m2m_relation?
from tortoise import fields, run_async, Tortoise
from tortoise.fields import ManyToManyRelation, ManyToManyField
from tortoise.models import Model
from tortoise.query_utils import Q
class MyModel(Model):
id = fields.IntField(pk=True)
properties: ManyToManyRelation["Property"]
class Property(Model):
id = fields.IntField(pk=True)
my_models: ManyToManyRelation["MyModel"] = ManyToManyField("models.MyModel", related_name='properties')
async def run():
# Generate the schema
await Tortoise.init({"connections": {"default_connection": {"engine": "tortoise.backends.sqlite", "credentials": {"file_path": ':memory:'},},}, "apps": {"models": {"models": ['__main__'], "default_connection": "default_connection"},},})
await Tortoise.generate_schemas()
m1 = await MyModel.create(id=1)
m2 = await MyModel.create(id=2)
p1 = await Property.create(id=1)
p2 = await Property.create(id=2)
await m1.properties.add(p1)
await m2.properties.add(p1, p2)
found = await MyModel.filter(
Q(
Q(properties__id=p1.id),
Q(properties__id=p2.id)
)
)
# Looking for [<MyModel 2>] because it has both relation p1 and p2 but get []
print(found)
run_async(run())
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 running the standalone SQLite example and tracing MyModel.filter with nested Q conditions and ManyToManyRelation handling. Check how multiple relation predicates are combined, then verify the query returns only MyModel 2 while still allowing additional relations. The issue is old and has an unanswered comment history, so confirm the expected behavior before starting.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python, sqlite
- Domain
- database
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100