'Provide pickling support. Normally, this just dispatches to Python\'s
standard handling. However, for models with deferred field loading, we
need to do things manually, as they\'re dynamically created classes and
only module-level classes can be pickled by the default path.'

def __reduce__(self):

    data = self.__dict__
    model = self.__class__
    defers = []
    pk_val = None
    if self._deferred:
        from django.db.models.query_utils import deferred_class_factory
        factory = deferred_class_factory
        for field in self._meta.fields:
            if isinstance(self.__class__.__dict__.get(field.attname), DeferredAttribute):
                defers.append(field.attname)
                if (pk_val is None):
                    obj = self.__class__.__dict__[field.attname]
                    model = obj.model_ref()
    else:
        factory = simple_class_factory
    return (model_unpickle, (model, defers, factory), data)
