diff --git a/docs/guide/defining-documents.rst b/docs/guide/defining-documents.rst index 7b8dcd5b..0caa4227 100644 --- a/docs/guide/defining-documents.rst +++ b/docs/guide/defining-documents.rst @@ -220,6 +220,20 @@ either a single field name, or a list or tuple of field names:: first_name = StringField() last_name = StringField(unique_with='first_name') +Skipping Document validation on save +------------------------------------ +You can also skip the whole document validation process by setting +``validate=False`` when caling the :meth:`~mongoengine.document.Document.save` +method:: + + class Recipient(Document): + name = StringField() + email = EmailField() + + recipient = Recipient(name='admin', email='root@localhost') + recipient.save() # will raise a ValidationError while + recipient.save(validate=False) # won't + Document collections ==================== Document classes that inherit **directly** from :class:`~mongoengine.Document` diff --git a/mongoengine/document.py b/mongoengine/document.py index e5dec145..af2a5e21 100644 --- a/mongoengine/document.py +++ b/mongoengine/document.py @@ -56,7 +56,7 @@ class Document(BaseDocument): __metaclass__ = TopLevelDocumentMetaclass - def save(self, safe=True, force_insert=False): + def save(self, safe=True, force_insert=False, validate=True): """Save the :class:`~mongoengine.Document` to the database. If the document already exists, it will be updated, otherwise it will be created. @@ -67,8 +67,10 @@ class Document(BaseDocument): :param safe: check if the operation succeeded before returning :param force_insert: only try to create a new document, don't allow updates of existing documents + :param validate: validates the document; set to ``False`` for skiping """ - self.validate() + if validate: + self.validate() doc = self.to_mongo() try: collection = self.__class__.objects._collection diff --git a/tests/document.py b/tests/document.py index 1160b353..c2e0d6f9 100644 --- a/tests/document.py +++ b/tests/document.py @@ -448,6 +448,16 @@ class DocumentTest(unittest.TestCase): self.assertEqual(person_obj['name'], 'Test User') self.assertEqual(person_obj['age'], 30) self.assertEqual(person_obj['_id'], person.id) + # Test skipping validation on save + class Recipient(Document): + email = EmailField(required=True) + + recipient = Recipient(email='root@localhost') + self.assertRaises(ValidationError, recipient.save) + try: + recipient.save(validate=False) + except ValidationError: + fail() def test_delete(self): """Ensure that document may be deleted using the delete method.