在mongoengine中使用StringField的choice功能时,希望能得到一个对用户更友好的错误提示,因此就要求能在写入数据库之前先进行一次验证已完成自定义提示。
多方查找后发现在BaseField中就包含了验证方法,代码如下:
if self.choices:
is_cls = isinstance(value, (Document, EmbeddedDocument))
value_to_check = value.__class__ if is_cls else value
err_msg = 'an instance' if is_cls else 'one'
if isinstance(self.choices[0], (list, tuple)):
option_keys = [k for k, v in self.choices]
if value_to_check not in option_keys:
msg = ('Value must be %s of %s' %
(err_msg, str(option_keys)))
self.error(msg)
elif value_to_check not in self.choices:
msg = ('Value must be %s of %s' %
(err_msg, str(self.choices)))
self.error(msg)
因为需要在Document外使用,所以对代码进行了包装,包装后代码如下:
def validate(value, choices):
if choices:
if isinstance(choices[0], (list, tuple)):
option_keys = [k for k, v in choices]
return value in option_keys
else:
return value in choices
else:
return False
如此即可方便的对数据进行验证。
举例如下:
class UserProfile(Document):
SEX_TYPE = (
('secret', '保密'),
('male', '男'),
('female', '女'),
)
sex = StringField(max_length=30, default='secret', choices=SEX_TYPE) # 性别
profile = UserProfile(sex='male').save()
print(profile.sex)
# male
profile.sex = 'error'
# raise ValidationError
print(validate('error',UserProfile.SEX_TYPE))
# False