'Descriptor to automatically dereference references.'

def __get__(self, instance, owner):

    if (instance is None):
        return self
    ReferenceField = _import_class('ReferenceField')
    GenericReferenceField = _import_class('GenericReferenceField')
    EmbeddedDocumentListField = _import_class('EmbeddedDocumentListField')
    dereference = (self._auto_dereference and ((self.field is None) or isinstance(self.field, (GenericReferenceField, ReferenceField))))
    _dereference = _import_class('DeReference')()
    self._auto_dereference = instance._fields[self.name]._auto_dereference
    if (instance._initialised and dereference and instance._data.get(self.name)):
        instance._data[self.name] = _dereference(instance._data.get(self.name), max_depth=1, instance=instance, name=self.name)
    value = super(ComplexBaseField, self).__get__(instance, owner)
    if isinstance(value, (list, tuple)):
        if (issubclass(type(self), EmbeddedDocumentListField) and (not isinstance(value, EmbeddedDocumentList))):
            value = EmbeddedDocumentList(value, instance, self.name)
        elif (not isinstance(value, BaseList)):
            value = BaseList(value, instance, self.name)
        instance._data[self.name] = value
    elif (isinstance(value, dict) and (not isinstance(value, BaseDict))):
        value = BaseDict(value, instance, self.name)
        instance._data[self.name] = value
    if (self._auto_dereference and instance._initialised and isinstance(value, (BaseList, BaseDict)) and (not value._dereferenced)):
        value = _dereference(value, max_depth=1, instance=instance, name=self.name)
        value._dereferenced = True
        instance._data[self.name] = value
    return value
