Made field validation lazier

This commit is contained in:
Harry Marr
2010-01-03 22:37:55 +00:00
parent 3574198210
commit b01596c942
3 changed files with 93 additions and 48 deletions

View File

@@ -35,17 +35,8 @@ class BaseField(object):
return value
def __set__(self, instance, value):
"""Descriptor for assigning a value to a field in a document. Do any
necessary conversion between Python and MongoDB types.
"""Descriptor for assigning a value to a field in a document.
"""
if value is not None:
try:
self.validate(value)
except (ValueError, AttributeError, AssertionError), e:
raise ValidationError('Invalid value for field of type "' +
self.__class__.__name__ + '"')
elif self.required:
raise ValidationError('Field "%s" is required' % self.name)
instance._data[self.name] = value
def to_python(self, value):
@@ -183,8 +174,6 @@ class BaseDocument(object):
else:
# Use default value if present
value = getattr(self, attr_name, None)
if value is None and attr_value.required:
raise ValidationError('Field "%s" is required' % attr_name)
setattr(self, attr_name, value)
@classmethod

View File

@@ -1,4 +1,5 @@
from base import DocumentMetaclass, TopLevelDocumentMetaclass, BaseDocument
from base import (DocumentMetaclass, TopLevelDocumentMetaclass, BaseDocument,
ValidationError)
from connection import _get_db
@@ -44,6 +45,7 @@ class Document(BaseDocument):
document already exists, it will be updated, otherwise it will be
created.
"""
self.validate()
object_id = self.__class__.objects._collection.save(self.to_mongo())
self.id = self._fields['id'].to_python(object_id)
@@ -54,6 +56,25 @@ class Document(BaseDocument):
object_id = self._fields['id'].to_mongo(self.id)
self.__class__.objects(id=object_id).delete()
def validate(self):
"""Ensure that all fields' values are valid and that required fields
are present.
"""
# Get a list of tuples of field names and their current values
fields = [(field, getattr(self, name))
for name, field in self._fields.items()]
# Ensure that each field is matched to a valid value
for field, value in fields:
if value is not None:
try:
field.validate(value)
except (ValueError, AttributeError, AssertionError), e:
raise ValidationError('Invalid value for field of type "' +
field.__class__.__name__ + '"')
elif field.required:
raise ValidationError('Field "%s" is required' % field.name)
@classmethod
def drop_collection(cls):
"""Drops the entire collection associated with this