Fix GenericReferenceField choices with DBRef and let it possible to set Document choice as string

This commit is contained in:
Emmanuel Leblond
2015-07-06 02:33:43 +02:00
parent 9671ca5ebf
commit a5fb009b62
3 changed files with 103 additions and 15 deletions

View File

@@ -165,26 +165,29 @@ class BaseField(object):
"""
pass
def _validate(self, value, **kwargs):
def _validate_choices(self, value):
Document = _import_class('Document')
EmbeddedDocument = _import_class('EmbeddedDocument')
choice_list = self.choices
if isinstance(choice_list[0], (list, tuple)):
choice_list = [k for k, v in choice_list]
# Choices which are other types of Documents
if isinstance(value, (Document, EmbeddedDocument)):
if not any(isinstance(value, c) for c in choice_list):
self.error(
'Value must be instance of %s' % unicode(choice_list)
)
# Choices which are types other than Documents
elif value not in choice_list:
self.error('Value must be one of %s' % unicode(choice_list))
def _validate(self, value, **kwargs):
# Check the Choices Constraint
if self.choices:
choice_list = self.choices
if isinstance(self.choices[0], (list, tuple)):
choice_list = [k for k, v in self.choices]
# Choices which are other types of Documents
if isinstance(value, (Document, EmbeddedDocument)):
if not any(isinstance(value, c) for c in choice_list):
self.error(
'Value must be instance of %s' % unicode(choice_list)
)
# Choices which are types other than Documents
elif value not in choice_list:
self.error('Value must be one of %s' % unicode(choice_list))
self._validate_choices(value)
# check validation argument
if self.validation is not None:

View File

@@ -1140,6 +1140,35 @@ class GenericReferenceField(BaseField):
.. versionadded:: 0.3
"""
def __init__(self, *args, **kwargs):
choices = kwargs.pop('choices', None)
super(GenericReferenceField, self).__init__(*args, **kwargs)
self._original_choices = choices or []
self._cooked_choices = None
def _validate_choices(self, value):
if isinstance(value, dict):
# If the field has not been dereferenced, it is still a dict
# of class and DBRef
if value.get('_cls') in [c.__name__ for c in self.choices]:
return
super(GenericReferenceField, self)._validate_choices(value)
@property
def choices(self):
if self._cooked_choices is None:
self._cooked_choices = []
for choice in self._original_choices:
if isinstance(choice, basestring):
choice = get_document(choice)
self._cooked_choices.append(choice)
return self._cooked_choices
@choices.setter
def choices(self, value):
self._original_choices = value
self._cooked_choices = None
def __get__(self, instance, owner):
if instance is None:
return self