Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while executing query

Tags:

django

I get an error message on this query

query = "select count(*) from pgns_game where raw_moves = %s"
params = ('a',)
total_rows = self.model.objects.raw(query, params)

and it says

InvalidQuery('Raw query must include the primary key')

I am clearly missing something but I don't know what. Any ideas?

like image 522
iJK Avatar asked Dec 05 '22 02:12

iJK


1 Answers

self.model.objects.raw() expects the query result to contain primary keys from the model self.model, so it can turn these into a list of objects for the function result.

What you really need to do is execute the SQL directly, and not through a manager. Your code will probably look like this:

from django.db import connection
cursor = connection.cursor()
cursor.execute("select count(*) from pgns_game where raw_moves = %s", ['a'])
total_rows = cursor.fetchone()

I haven't tried this myself, though.

like image 62
Mike DeSimone Avatar answered Jan 02 '23 12:01

Mike DeSimone