VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app

How to Fix Raw query must include the primary key with Django ORM

       

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 w/ #django #sql #orm #python #troubleshooting #debug