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
withmodel._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'sCast
function with theid
property to cast the primary key of the model into a string, which will automatically de-aliaspk
to the name of primary key field and use the correct table alias in the resulting query.