执行查询时出错

iJK*_*iJK 4 django

我收到有关此查询的错误消息

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

它说

InvalidQuery('Raw query must include the primary key')
Run Code Online (Sandbox Code Playgroud)

我显然遗漏了一些东西,但我不知道是什么.有任何想法吗?

Mik*_*one 16

self.model.objects.raw()期望查询结果包含模型中的主键self.model,因此它可以将这些键转换为函数结果的对象列表.

你真正需要做的是直接执行SQL,而不是通过管理器. 您的代码可能如下所示:

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

不过,我自己也没试过.