SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

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

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
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