django rest框架:通过序列化程序validate()方法设置字段级错误 [英] django rest framework: set field-level error from serializer validate() method
问题描述
我有一个序列化程序,它根据其他字段的值来验证字段,在错误响应中,我想将每个字段错误都显示为一个字段错误,而不是在 non_field_errors下显示所有内容,如果我在对象级别的validate方法中引发ValidationError。下面是我要实现的目标的说明:
I have a serializer that validates fields based on the values of other fields, In the error response I would like to show each field error as a field error as opposed to showing everything under "non_field_errors" which is what would happen if I were to raise a ValidationError in the object-level validate method. Below is an illustration of what I'm trying to achieve:
MySerializer(ModelSerializer):
...
def validate(self, data):
field_val1 = data['field_val1']
field_val2 = data['field_val2']
if not self._is_field_valid(field_val1, field_val2):
# The below line is how I would do what I want with Django
# Forms, however, it's not valid in DRF
self._errors['field_val1'] = 'this field is not valid'
所需的错误响应为:
{'field_val1': ['this field is not valid']}
推荐答案
我在此页的 BaseSerializer部分中,有一个示例显示ValidationError可以在初始化时采用字典参数。
I figured it out, on this page of the documentation in the "BaseSerializer" section, there's an example that shows ValidationError can take a dictionary argument upon initialization.
如果我 raise ValidationError({'field_val1':['此字段无效']})
得到我想要的JSON响应。
If I raise ValidationError({'field_val1': ['this field is not valid']})
I get the JSON response I want.
这篇关于django rest框架:通过序列化程序validate()方法设置字段级错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!