tortoise / tortoise/tortoise-orm

A question about filter queries, is it unsupported or a bug?

Open
#2,003 5 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

tortoise-orm == 0.24.0

tags = fields.ManyToManyField(
        'blog.Tags',
        related_name='blogs',
        description='tag',
        through="blog_blog_tags",
        forward_key="tags_id", 
        backward_key="blog_id"  
    )

I have a simple query requirement that needs to retrieve data with tag ids 469 and 7107 simultaneously, but there is a prerequisite condition: only need to query simultaneously when new is true.

Initially, the code was like this

blog_queryset = Blog.filter(tags__id=469)
if new:
    blog_queryset.filter(tags__id=7107)

But I found that the query results are empty,When handling many-to-many relationships, using .filter(tags__id=X).filter(tags__id=Y) consecutively does not produce an intersection query.

Then I tried to query using Q expressions.

query.filter(Q(tags__id=469) & Q(tags__id=7107))

I found that the result is still empty. But strangely, when I changed & to and, I was able to get the correct query results, which were no longer empty.

query.filter(Q(tags__id=469) and Q(tags__id=7107))

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

No repository file, test, or entry point is named. Reproduce the ManyToMany setup and compare the chained filters with the two Q-expression forms shown, including generated queries and returned rows. Done means the behavior is confirmed and covered by a focused regression test or clearly identified as supported usage.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend, database
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.