Created
May 16, 2011 16:07
-
-
Save Suor/974735 to your computer and use it in GitHub Desktop.
Efficient pickling of django models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models import Model | |
from itertools import izip | |
def attnames(cls, _cache={}): | |
try: | |
return _cache[cls] | |
except KeyError: | |
_cache[cls] = [f.attname for f in cls._meta.fields] | |
return _cache[cls] | |
def model_unpickle(cls, data): | |
obj = cls.__new__(cls) | |
obj.__dict__.update(izip(attnames(cls), data)) | |
return obj | |
model_unpickle.__safe_for_unpickle__ = True | |
def Model__reduce__(self): | |
if self._deferred: | |
return original_Model__reduce__(self) | |
else: | |
cls = self.__class__ | |
data = self.__dict__.copy() | |
vector = map(data.pop, attnames(cls)) | |
return (model_unpickle, (cls, vector), data) | |
original_Model__reduce__ = Model.__reduce__ | |
Model.__reduce__ = Model__reduce__ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See also django-pickling package