tortoise-orm icon indicating copy to clipboard operation
tortoise-orm copied to clipboard

If "id" is on values list, group by does not add the table name

Open daniel-hartmann opened this issue 1 year ago • 2 comments

Describe the bug When filtering for a foreign key value, using group_by and values, if "id" is in values, the group by fails to add the table name.

To Reproduce sql = await MyModel.filter(members__user_id=1).group_by('id').values('id').sql() This will generate something like: SELECT "mymodel"."id" "id" FROM "mymodel" LEFT OUTER JOIN "mymodel_mymodeluser" ON "mymodel"."id"="mymodel_mymodeluser"."mymodel_id" LEFT OUTER JOIN "mymodeluser" ON "mymodel_mymodeluser"."mymodeluser_id"="mymodeluser"."id" WHERE "mymodeluser"."user_id"=1 GROUP BY "id"

If you execute that, it will fail with: tortoise.exceptions.OperationalError: column reference "id" is ambiguous

Expected behavior

Add the table name in the group by: SELECT "mymodel"."id" "id" FROM "mymodel" LEFT OUTER JOIN "mymodel_mymodeluser" ON "mymodel"."id"="mymodel_mymodeluser"."mymodel_id" LEFT OUTER JOIN "mymodeluser" ON "mymodel_mymodeluser"."mymodeluser_id"="mymodeluser"."id" WHERE "mymodeluser"."user_id"=1 GROUP BY "mymodel"."id"

daniel-hartmann avatar May 15 '23 12:05 daniel-hartmann

I solved this issue by changing the 'id' in the values:

sql = MyModel.filter(members__user_id=1).group_by('id').values(mymodel_id='id').sql()
print(sql)

Output:

SELECT
  "mymodel"."id" "mymodel_id"
FROM
  "mymodel"
  LEFT OUTER JOIN "mymodel_mymodeluser" ON "mymodel"."id" = "mymodel_mymodeluser"."mymodel_id"
  LEFT OUTER JOIN "mymodeluser" ON "mymodel_mymodeluser"."mymodeluser_id" = "mymodeluser"."id"
WHERE
  "mymodeluser"."user_id" = 1
GROUP BY
  "mymodel"."id"

Running query:

query = await MyModel.filter(members__user_id=1).group_by('id').all().values(mymodel_id='id')
print(query)

Output query:

[{'mymodel_id': 1}, {'mymodel_id': 2}, {'mymodel_id': 3}]

thiago-felipe-99 avatar Feb 16 '24 19:02 thiago-felipe-99