是否可以在数据库中腌制或以某种方式存储 django 查询?这是行不通的:
u = User.objects.all
import cPickle
pickled_query = cPickle.dumps(u) # and store the pickled_query in a db-field.
有什么想法吗?
Updated:
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
还是不完全满意。我知道 QuerySet 很懒,所以执行 s2.model.objects.all() 不会执行获取所有用户的查询?
There's 文档 http://docs.djangoproject.com/en/dev/ref/models/querysets/#pickling-querysets为了那个原因。基本上,腌制query
如果要重新创建 SQL 查询,请使用属性;如果要腌制当前结果的快照,请腌制整个查询集。
如果你腌制了结果,你的例子会做后者all()
而不是绑定方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)