我开始在我的应用程序中使用django-rest-framework,我对序列化程序验证有疑问。 在文档中,我发现了这个用于对象验证的例子:
from rest_framework import serializers
class EventSerializer(serializers.Serializer):
description = serializers.CharField(max_length=100)
start = serializers.DateTimeField()
finish = serializers.DateTimeField()
def validate(self, attrs):
"""
Check that the start is before the stop.
"""
if attrs['start'] > attrs['finish']:
raise serializers.ValidationError("finish must occur after start")
return attrs
返回以下内容:
{"non_field_errors": ["finish must occur after start"]}
我的问题是,如何找出哪些字段导致验证失败? 在这种情况下,attrs [' start']和attrs [' finish']。 最后我想要这样的事情:
{"non_field_errors": ["finish must occur after start"],
"start": ["finish must occur after start"],
"finish": ["finish must occur after start"]}
这样我就可以标记负责的表单字段。 我希望这个问题很清楚。谢谢!
答案 0 :(得分:3)
创建ValidationError
时,可以传入字典而不是字符串。字典期望key
是字段名称,value
是错误字符串。
def validate(self, attrs):
"""
Check that the start is before the stop.
"""
if attrs['start'] > attrs['finish']:
raise serializers.ValidationError({"finish": "finish must occur after start"})
return attrs
这应该产生以下行的输出:
{"start": ["finish must occur after start"],
"finish": ["finish must occur after start"]}
这听起来像你在寻找。