问题
Is it possible to pickle or somehow store a django query in the database? This won`t work :
u = User.objects.all
import cPickle
pickled_query = cPickle.dumps(u) # and store the pickled_query in a db-field.
Any thoughts?
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.
Now that's what I want to do. I know this actual piece of code won`t run, but it shows my intention; to store a query, not the result, and execute that query at some point in the future.
Update #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
Still not completly satisfied. I know QuerySets are lazy so doing s2.model.objects.all() won't execute a query fetching all users?
回答1:
There's documentation for that. Basically, pickle the query attribute if you want to recreate the SQL query, and pickle the whole queryset if you want to pickle a snapshot of the current results.
Your example would do the latter, if you pickled the result of all() instead of the bound method.
来源:https://stackoverflow.com/questions/5715479/pickle-a-django-query