我开始为我的应用程序使用 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"]}
这样我就可以标记负责的表单字段。我希望这个问题很清楚。谢谢!