Check if undefined fields are supplied on document

If an undefined field is supplied to a document instance, a
`FieldDoesNotExist` Exception will be raised.
This commit is contained in:
Rik 2013-09-02 18:11:50 +02:00 committed by Wilson Júnior
parent 74a89223c0
commit 4cca9f17df
2 changed files with 14 additions and 1 deletions

View File

@ -12,7 +12,7 @@ from bson.son import SON
from mongoengine import signals from mongoengine import signals
from mongoengine.common import _import_class from mongoengine.common import _import_class
from mongoengine.errors import (ValidationError, InvalidDocumentError, from mongoengine.errors import (ValidationError, InvalidDocumentError,
LookUpError) LookUpError, FieldDoesNotExist)
from mongoengine.python_support import PY3, txt_type from mongoengine.python_support import PY3, txt_type
from mongoengine.base.common import get_document, ALLOW_INHERITANCE from mongoengine.base.common import get_document, ALLOW_INHERITANCE
@ -61,6 +61,15 @@ class BaseDocument(object):
signals.pre_init.send(self.__class__, document=self, values=values) signals.pre_init.send(self.__class__, document=self, values=values)
# Check if there are undefined fields supplied, if so raise an
# Exception.
for var in values.keys():
if var not in self._fields.keys():
msg = (
"The field '{}' does not exist on the document '{}'"
).format(var, self._class_name)
raise FieldDoesNotExist(msg)
if self.STRICT and not self._dynamic: if self.STRICT and not self._dynamic:
self._data = StrictDict.create(allowed_keys=self._fields_ordered)() self._data = StrictDict.create(allowed_keys=self._fields_ordered)()
else: else:

View File

@ -40,6 +40,10 @@ class NotUniqueError(OperationError):
pass pass
class FieldDoesNotExist(Exception):
pass
class ValidationError(AssertionError): class ValidationError(AssertionError):
"""Validation exception. """Validation exception.