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.common import _import_class
from mongoengine.errors import (FieldDoesNotExist, InvalidDocumentError,
LookUpError, ValidationError)
LookUpError, ValidationError, OperationError)
from mongoengine.python_support import PY3
__all__ = ('BaseDocument', 'NON_FIELD_ERRORS')
@ -28,7 +28,8 @@ NON_FIELD_ERRORS = '__all__'
class BaseDocument(object):
__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_lock = True
@ -166,10 +167,12 @@ class BaseDocument(object):
except AttributeError:
self__created = True
if (self._is_document and not self__created and
name in self._meta.get('shard_key', tuple()) and
self._data.get(name) != value):
OperationError = _import_class('OperationError')
if (
self._is_document and
not self__created and
name in self._meta.get('shard_key', tuple()) and
self._data.get(name) != value
):
msg = "Shard Keys are immutable. Tried to update %s" % name
raise OperationError(msg)

View File

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