Weh*_*olt 4 python django pickle
是否有可能在数据库中腌制或以某种方式存储django查询?这不会起作用:
u = User.objects.all
import cPickle
pickled_query = cPickle.dumps(u) # and store the pickled_query in a db-field.
Run Code Online (Sandbox Code Playgroud)
有什么想法吗?
更新:
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.
Run Code Online (Sandbox Code Playgroud)
现在这就是我想要做的.我知道这段实际的代码不会运行,但它表明了我的意图; 存储查询,而不是结果,并在将来的某个时刻执行该查询.
更新#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
Run Code Online (Sandbox Code Playgroud)
仍然没有完全满意.我知道QuerySets是懒惰的,所以s2.model.objects.all()不会执行查询获取所有用户?
| 归档时间: |
|
| 查看次数: |
7234 次 |
| 最近记录: |