Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
daniel-hartmann opened this issue May 15, 2023 · 2 comments · Fixed by #1766
Closed

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

daniel-hartmann opened this issue May 15, 2023 · 2 comments · Fixed by #1766

Comments

@daniel-hartmann
Copy link

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"

@thiago-felipe-99
Copy link

thiago-felipe-99 commented Feb 16, 2024

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}]

@windows8prew
Copy link

It's definitely a bug

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants