tortoise / tortoise/tortoise-orm

Error in SQL to build QuerySet. A Model with multiple ForeignKeyField referring to the same model.

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

Describe the bug

class Range(Model):
    min = fields.ForeignKeyField("models.Value", null=True, related_name="range_min")
    max = fields.ForeignKeyField("models.Value", null=True, related_name="range_max")


class Value(Model):
    value = fields.IntField()
min = await Value.create(value=1)
max = await Value.create(value=5)
await Range.create(min=min, max=max)
    
# Get the Value of the Range containing 3.
values = await Value.filter(Q(range_min__max__value__gt=3, 
                              range_max__min__value__lt=3, 
                              join_type="OR"))

# Expect: 
#     Two Values are returned
# Result: 
#    Only the first `range_min` specified in Q is returned.
assert 2 == len(values)

Generated queries.

SELECT "value"."id","value"."value"
FROM "value"
    LEFT OUTER JOIN "range" ON "value"."id"="range"."min_id"
    LEFT OUTER JOIN "value" "range__max" ON "range__max"."id"="range"."max_id"
    LEFT OUTER JOIN "value" "range__min" ON "range__min"."id"="range"."min_id"
WHERE "range__max"."value">3 OR "range__min"."value"<3

Queries to expect.

SELECT "value"."id","value"."value"
FROM "value"
    LEFT OUTER JOIN "range" ON "value"."id"="range"."min_id" OR "value"."id"="range"."max_id"
    LEFT OUTER JOIN "value" "range__max" ON "range__max"."id"="range"."max_id"
    LEFT OUTER JOIN "value" "range__min" ON "range__min"."id"="range"."min_id"
WHERE "range__max"."value">3 OR "range__min"."value"<3

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 Range and Value model definitions, the Value.filter query, and the generated SQL in the issue. Reproduce the query with both ForeignKeyField relations pointing to Value and inspect how the OR condition is translated into joins. Done means the generated join condition matches the expected SQL and the query returns both matching Values.

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.