我正在尝试对Mongoengine modify操作应用自定义验证,如下所示:
class Form(Document):
fields = ListField(EmbeddedDocumentField(Field))
def modify(self, *args, **kwargs):
for field in self.fields:
if not [field for field in self.fields if field.type == "email"]:
raise ValidationError("Form must have an email field")
super(Form, self).modify(**kwargs)
def update_form(self, modify_kwargs):
return self.modify(**modify_kwargs)
但是,当我致电update_form
时,自定义验证不会在modify
中考虑更新的数据。是否有某种预挂钩用于进行此类验证?
答案 0 :(得分:1)
您正在验证对象字段属性而不是kwargs。但请确保每个字段都是包含.type的对象。你不应该使用python保留字类型。
class Form(Document):
fields = ListField(EmbeddedDocumentField(Field))
def modify(self, *args, **kwargs):
if not [field for field in kwargs.get('fields', []) if field.type == "email"]:
raise ValidationError("Form must have an email field")
super(Form, self).modify(**kwargs)
def update_form(self, modify_kwargs):
return self.modify(**modify_kwargs)