tortoise-orm: Annotate on recursive relation giving error on PostgreSQL
Hello, I’m getting this PG error while trying to do a count on a recursive relationship.
tortoise.exceptions.OperationalError: column “task.estimated_start_date” must appear in the GROUP BY clause or be used in an aggregate function
class Task(BaseModel):
mother = fields.ForeignKeyField('models.Task', null=True, related_name="children")
#Some code later...
tasks = await Task.filter(mother=None).annotate(children_count=Count("children"))
Am I doing something wrong?
What I’m trying to achieve with my query, is a hierarchical view of the tasks, first I’m getting the “outer” ones, and then checking if they have any children so then I will display a dropdown arrow that will asynchronous load the children and so on.
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 15 (8 by maintainers)
Commits related to this issue
- Fix joining with self by reverse-foreign-key for filtering and annotation (#333) — committed to tortoise/tortoise-orm by grigi 4 years ago
- Fix joining with self by reverse-foreign-key for filtering and annotation (#333) — committed to tortoise/tortoise-orm by grigi 4 years ago
- Many small Function fixes (#333) — committed to tortoise/tortoise-orm by grigi 4 years ago
- Fix the aggregates using the wrong side of the join when doing a self-referential aggregate. (#333) — committed to tortoise/tortoise-orm by grigi 4 years ago
Release 0.16.4 os out with the fix, please confirm.
It should be fixed in next release. You can test out develop doing a
pip install https://github.com/tortoise/tortoise-orm/archive/develop.zip@grigi Yep, just updated dependencies and it works now, thanks for the very quick fix!
Built a test for this, got the same error:
The SQL generated looks like:
🤣 The last bit is all confused, instead of differentiating between
employeeandemployee2everything now has the 2… This is almost identical to the bug we had with filtering on a self-referential entry.