tortoise / tortoise/tortoise-orm
Error in SQL to build QuerySet. A Model with multiple ForeignKeyField referring to the same model.
Open
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
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 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