我的Django的網站最近開始從我的緩存代碼拋出錯誤,我想不通爲什麼...Django的cache.set()導致重複鍵錯誤
我打電話:
from django.core.cache import cache
cache.set('blogentry', some_value)
而且Django在拋出的錯誤是:
TransactionManagementError: This code isn't under transaction management
但看PostgreSQL數據庫日誌,似乎從這個錯誤中幹:
STATEMENT: INSERT INTO cache_table (cache_key, value, expires) VALUES (E'blogentry', E'pickled_version_of_some_value', E'2009-07-27 11:10:26')
ERROR: duplicate key value violates unique constraint "cache_table_pkey"
對於我的生活,我無法弄清楚爲什麼Django試圖做INSERT而不是UPDATE。有什麼想法嗎?
cursor.execute("SELECT cache_key, expires FROM %s WHERE cache_key = %%s" % self._table, [key])
try:
result = cursor.fetchone()
if result and (mode == 'set' or
(mode == 'add' and result[1] < now)):
cursor.execute("UPDATE %s SET value = %%s, expires = %%s WHERE cache_key = %%s" % self._table, [encoded, str(exp), key])
else:
cursor.execute("INSERT INTO %s (cache_key, value, expires) VALUES (%%s, %%s, %%s)" % self._table, [key, encoded, str(exp)])
所以我說,你正在做的INSERT INTO,而不是更新,因爲結果計算爲false:
是不是緩存到數據庫有一種破壞緩存的目的? – thedz 2009-07-27 21:52:07
取決於你正在緩存什麼。 – 2009-07-27 22:14:36
我將它編輯爲「blogentry」,但它實際上緩存了博客邊欄小部件的大量相關數據。 – 2009-07-27 23:54:07