2010-05-26 123 views
4

我对这个查询错误而执行查询

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

得到一个错误信息,它说

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

我清楚地失去了一些东西,但我不知道是什么。有任何想法吗?

+0

在这里说的文档(http://docs.djangoproject.com/en/1.2/topics/db/sql/#deferring-model-fields):“只有一个领域,你不能离开 - 主键字段Django使用主键来标识模型实例,因此它必须始终包含在原始查询中,如果忘记包含主键,则会引发InvalidQuery异常。 – bernie 2010-05-26 03:19:37

回答

16

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

你真正需要做的是execute the SQL directly, and not through a manager.您的代码可能会是这样的:

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

我没有尝试这样做我自己,虽然。

+0

谢谢,我不知道。 – iJK 2010-05-26 03:25:00