cleaner code + prefer top-level import over _import_class

This commit is contained in:
Stefan Wojcik 2016-12-08 08:18:33 -05:00
parent f6b8899bba
commit 8f657e0f7d
2 changed files with 20 additions and 10 deletions

View File

@ -18,7 +18,7 @@ from mongoengine.base.datastructures import (BaseDict, BaseList,
from mongoengine.base.fields import ComplexBaseField from mongoengine.base.fields import ComplexBaseField
from mongoengine.common import _import_class from mongoengine.common import _import_class
from mongoengine.errors import (FieldDoesNotExist, InvalidDocumentError, from mongoengine.errors import (FieldDoesNotExist, InvalidDocumentError,
LookUpError, ValidationError) LookUpError, ValidationError, OperationError)
from mongoengine.python_support import PY3 from mongoengine.python_support import PY3
__all__ = ('BaseDocument', 'NON_FIELD_ERRORS') __all__ = ('BaseDocument', 'NON_FIELD_ERRORS')
@ -28,7 +28,8 @@ NON_FIELD_ERRORS = '__all__'
class BaseDocument(object): class BaseDocument(object):
__slots__ = ('_changed_fields', '_initialised', '_created', '_data', __slots__ = ('_changed_fields', '_initialised', '_created', '_data',
'_dynamic_fields', '_auto_id_field', '_db_field_map', '__weakref__') '_dynamic_fields', '_auto_id_field', '_db_field_map',
'__weakref__')
_dynamic = False _dynamic = False
_dynamic_lock = True _dynamic_lock = True
@ -166,10 +167,12 @@ class BaseDocument(object):
except AttributeError: except AttributeError:
self__created = True self__created = True
if (self._is_document and not self__created and if (
name in self._meta.get('shard_key', tuple()) and self._is_document and
self._data.get(name) != value): not self__created and
OperationError = _import_class('OperationError') name in self._meta.get('shard_key', tuple()) and
self._data.get(name) != value
):
msg = "Shard Keys are immutable. Tried to update %s" % name msg = "Shard Keys are immutable. Tried to update %s" % name
raise OperationError(msg) raise OperationError(msg)

View File

@ -714,12 +714,19 @@ class ListField(ComplexBaseField):
def prepare_query_value(self, op, value): def prepare_query_value(self, op, value):
if self.field: if self.field:
if op in ('set', 'unset', None) and (
not isinstance(value, six.string_types) and # If the value is iterable and it's not a string nor a
not isinstance(value, BaseDocument) and # BaseDocument, call prepare_query_value for each of its items.
hasattr(value, '__iter__')): if (
op in ('set', 'unset', None) and
hasattr(value, '__iter__') and
not isinstance(value, six.string_types) and
not isinstance(value, BaseDocument)
):
return [self.field.prepare_query_value(op, v) for v in value] return [self.field.prepare_query_value(op, v) for v in value]
return self.field.prepare_query_value(op, value) return self.field.prepare_query_value(op, value)
return super(ListField, self).prepare_query_value(op, value) return super(ListField, self).prepare_query_value(op, value)