tortoise / tortoise/tortoise-orm

Cannot annotate two different ReverseRelation

Open
#911 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

class Player(Model):
    id = fields.IntField(pk=True)
    id_player_score_f: fields.ReverseRelation["Score"]
    id_player_score_s: fields.ReverseRelation["Score"]

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

st = Player.all().annotate(mf=Max("id_player_score_f__id"),ms=Max("id_player_score_s__id")).sql()

or

st = Player.all().annotate(mf=Max("id_player_score_f__id")).annotate(ms=Max("id_player_score_s__id")).sql()


Results in:

SELECT "players"."id", MAX("scores"."id") "mf", MAX("scores"."id") "ms" FROM "players" LEFT OUTER JOIN "scores" ON "players"."id"="scores"."f_id" GROUP BY "players"."id"

Expected:

SELECT "players"."id", MAX("scores1"."id") "mf", MAX("scores2"."id") "ms" FROM "players" LEFT OUTER JOIN "scores1" ON "players"."id"="scores1"."f_id" LEFT OUTER JOIN "scores2" ON "players"."id"="scores2"."s_id" GROUP BY "players"."id"

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 Player/Score reproducer and the Player.all().annotate(...).sql() entry point. Trace how each ReverseRelation path becomes a join, comparing the generated SQL with the expected separate aliases and f_id/s_id joins. Done when combined and chained annotations generate both distinct joins, with regression coverage for these cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
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.