gpt4 book ai didi

python - pickle Django 查询?

转载 作者:太空狗 更新时间:2023-10-30 02:49:57 24 4
gpt4 key购买 nike

是否有可能 pickle 或以某种方式将 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() 不会执行获取所有用户的查询?

最佳答案

documentation为了那个原因。基本上,如果您想重新创建 SQL 查询,则 pickle query 属性,如果您想 pickle 当前结果的快照,则 pickle 整个查询集。

如果您 pickle all() 的结果而不是绑定(bind)方法,您的示例将执行后者。

关于python - pickle Django 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5715479/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com