Added clean method to documents for pre validation data cleaning (MongoEngine/mongoengine#60)

This commit is contained in:
Ross Lawley
2012-11-07 12:12:28 +00:00
parent 7073b9d395
commit 1986e82783
8 changed files with 150 additions and 25 deletions

View File

@@ -4,6 +4,7 @@ Changelog
Changes in 0.8
==============
- Added clean method to documents for pre validation data cleaning (MongoEngine/mongoengine#60)
- Added support setting for read prefrence at a query level (MongoEngine/mongoengine#157)
- Added _instance to EmbeddedDocuments pointing to the parent (MongoEngine/mongoengine#139)
- Inheritance is off by default (MongoEngine/mongoengine#122)

View File

@@ -38,6 +38,34 @@ already exist, then any changes will be updated atomically. For example::
.. seealso::
:ref:`guide-atomic-updates`
Pre save data validation and cleaning
-------------------------------------
MongoEngine allows you to create custom cleaning rules for your documents when
calling :meth:`~mongoengine.Document.save`. By providing a custom
:meth:`~mongoengine.Document.clean` method you can do any pre validation / data
cleaning.
This might be useful if you want to ensure a default value based on other
document values for example::
class Essay(Document):
status = StringField(choices=('Published', 'Draft'), required=True)
pub_date = DateTimeField()
def clean(self):
"""Ensures that only published essays have a `pub_date` and
automatically sets the pub_date if published and not set"""
if self.status == 'Draft' and self.pub_date is not None:
msg = 'Draft entries should not have a publication date.'
raise ValidationError(msg)
# Set the pub_date for published items if not set.
if self.status == 'Published' and self.pub_date is None:
self.pub_date = datetime.now()
.. note::
Cleaning is only called if validation is turned on and when calling
:meth:`~mongoengine.Document.save`.
Cascading Saves
---------------
If your document contains :class:`~mongoengine.ReferenceField` or