2010-05-26 150 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