2011-04-19 30 views
4

是否有可能在數據庫中醃製或以某種方式存儲django查詢?這沒有工作:泡菜django查詢?

u = User.objects.all 
import cPickle 
pickled_query = cPickle.dumps(u) # and store the pickled_query in a db-field. 

有什麼想法?

更新時間:

import cPickle 

class CustomData(models.Model): 
    name = models.CharField(max_length = 30) 
    pickled_query = models.CharField(max_length = 300) 

def get_custom_result(self): 
    q = cPickle.loads(self.pickled_query) 
    return q() 

>>> cd = CustomData(name="My data", pickled_query=cPickle.dumps(User.objects.all)) 
>>> cd.save() 
>>> for item in cd.get_custom_result(): print item 
# prints all the users in the database, not printing the query result 
# when pickled, but when called like cd.get_custom_result(), that is when 
# the query is actually executed. 

現在這就是我想做的事情。我知道這段代碼不會運行,但它顯示了我的意圖;存儲查詢而不是結果,並在將來某個時刻執行該查詢。

更新#2:

>>> from django.contrib.auth.models import User 
# adds two users; super and test 
>>> u = User.objects.filter(username = 'test') 
>>> import cPickle 
>>> s = cPickle.dumps(u.query) 
>>> s2 = cPickle.loads(s) 
>>> o = s2.model.objects.all() 
>>> o.query = s2 
>>> for i in o: print i 
... 
super 

仍然沒有完全地滿足。我知道QuerySets是懶惰的,所以做s2.model.objects.all()不會執行提取所有用戶的查詢?

+0

Django已經可以序列化對象。它只有一個序列化模塊。你讀過這個了嗎? http://docs.djangoproject.com/en/1.3/topics/serialization/ – 2011-04-19 11:18:43

+0

您是否試圖醃製查詢或查詢結果? – Canuteson 2011-04-19 11:31:38

+0

我不酸洗查詢結果,只是方法,所以我可以稍後取消它並做:query_method = cpickle.loads(pickled_query);對於query_method()中的orm_instance:print orm_instance。這是否使它更清晰? – Weholt 2011-04-19 11:38:20

回答

5

這裏有documentation。基本上,如果你想重新創建SQL查詢,就可以使用query屬性,並且如果你想醃製當前結果的快照,就可以使用整個查詢集。

如果你醃製all()而不是綁定方法的結果,你的示例將執行後者。

+0

啊!我明白了,但不會全部()執行查詢?我需要知道查詢與哪個模型有關? – Weholt 2011-04-19 12:39:00

+1

查詢具有「模型」屬性。如果你醃製QuerySet(而不是Query),那麼當前的結果集將被序列化,並且需要執行它。 Btw:all()不執行查詢。 – emulbreh 2011-04-19 13:46:18

+0

@Weholt:不,all()不執行查詢。只有當你真正嘗試迭代結果時,它纔會被執行。 – vartec 2011-04-19 13:59:40