Written by Sean Behan on Sat Jul 15th 2017

When running raw SQL queries in Django you must include a primary key otherwise an invalid query exception is raised. Normally this is fine but when running more complex queries a primary key may not be available or even make sense.

There is a simple work around, however. You can just alias 1 as id in your query (or any number) and Django will not complain.

Model.objects.raw('select count(*) from records')

Will raise this exception

    raise InvalidQuery('Raw query must include the primary key') 
    django.db.models.query_utils.InvalidQuery: Raw query must include the primary key

By changing the query to this

Model.objects.raw('select 1 id, count(*) from records')

Everything will work as expected. Simple.


Tagged with..
#django #sql #orm #python #troubleshooting #debug

Just finishing up brewing up some fresh ground comments...