Pickle a Django查询?

时间:2011-04-19 11:14:46

标签: python django pickle

是否有可能在数据库中腌制或以某种方式存储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()不会执行查询获取所有用户?

1 个答案:

答案 0 :(得分:5)

documentation。基本上,如果要重新创建SQL查询,请选择query属性,如果要挑选当前结果的快照,则选择整个查询集。

如果你腌制all()的结果而不是绑定方法,你的例子会做后者。