泡一个Django查询? [英] Pickle a django query?
问题描述
是否可以在数据库中腌制或以某种方式存储Django查询?这是行不通的:
Is it possible to pickle or somehow store a django query in the database? This won`t work :
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.
现在这就是我想要做的.我知道这段实际的代码不会运行,但这表明了我的意图.存储查询而不是结果,并在将来某个时候执行该查询.
Now that's what I want to do. I know this actual piece of code won`t run, but it shows my intention; to store a query, not the result, and execute that query at some point in the future.
更新#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
仍未完全满意.我知道QuerySet是惰性的,因此执行s2.model.objects.all()不会执行获取所有用户的查询吗?
Still not completly satisfied. I know QuerySets are lazy so doing s2.model.objects.all() won't execute a query fetching all users?
推荐答案
有文档.基本上,如果要重新创建SQL查询,请腌制query
属性,如果要对当前结果的快照进行腌制,则对整个查询集进行腌制.
There's documentation for that. Basically, pickle the query
attribute if you want to recreate the SQL query, and pickle the whole queryset if you want to pickle a snapshot of the current results.
如果您腌制all()
的结果而不是绑定方法,您的示例将使用后者.
Your example would do the latter, if you pickled the result of all()
instead of the bound method.
这篇关于泡一个Django查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!