Skip to content

Conversation

@ercpe
Copy link

@ercpe ercpe commented Aug 14, 2024

Using RawSQL with model._meta.pk.db_column will add a verbatim SQL expression into the query. In this case, a reference to the primary key column, although without the proper table alias. This leads to a SQL error for QuerySets which already have a JOIN due to an ambiguous column (e.g. id). Use Django's Cast function with the id property to cast the primary key of the model into a string, which will automatically de-alias pk to the name of primary key field and use the correct table alias in the resulting query.

Using `RawSQL` with `model._meta.pk.db_column` will add a verbatim SQL expression into the query. In this case, a reference to the primary key column, although without the proper table alias. This leads to a SQL error for QuerySets which already have a JOIN due to an ambiguous column (e.g. `id`).
Use Django's `Cast` function with the `id` property to cast the primary key of the model into a string, which will automatically de-alias `pk` to the name of primary key field and use the correct table alias in the resulting query.
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 this pull request may close these issues.

1 participant