From 8f657e0f7d10746c437f757ce9a35d4bc81ca79b Mon Sep 17 00:00:00 2001 From: Stefan Wojcik Date: Thu, 8 Dec 2016 08:18:33 -0500 Subject: [PATCH] cleaner code + prefer top-level import over _import_class --- mongoengine/base/document.py | 15 +++++++++------ mongoengine/fields.py | 15 +++++++++++---- 2 files changed, 20 insertions(+), 10 deletions(-) diff --git a/mongoengine/base/document.py b/mongoengine/base/document.py index 3fa7ff65..33d1a50e 100644 --- a/mongoengine/base/document.py +++ b/mongoengine/base/document.py @@ -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) diff --git a/mongoengine/fields.py b/mongoengine/fields.py index 757703f2..e23e115a 100644 --- a/mongoengine/fields.py +++ b/mongoengine/fields.py @@ -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)