泡一个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
仍然不完全满意。我知道QuerySet是惰性的,因此执行s2.model.objects.all()不会执行获取所有用户的查询吗?
没有找到相关结果
已邀请:
1 个回复
魄龟呸筹