是否有可能在数据库中腌制或以某种方式存储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()不会执行提取所有用户的查询?
Django已经可以序列化对象。它只有一个序列化模块。你读过这个了吗? http://docs.djangoproject.com/en/1.3/topics/serialization/ – 2011-04-19 11:18:43
您是否试图腌制查询或查询结果? – Canuteson 2011-04-19 11:31:38
我不酸洗查询结果,只是方法,所以我可以稍后取消它并做:query_method = cpickle.loads(pickled_query);对于query_method()中的orm_instance:print orm_instance。这是否使它更清晰? – Weholt 2011-04-19 11:38:20