我有一个接受JSON的API。JSON数据具有一个称为的键type
,该键应该是一个选择字段,并且具有5种指定类型之间的值。说出A,B,C,D和E。
JSON可以具有不同的字段,具体取决于值是A,B,C,D还是E。如何验证可能存在或不存在的其他字段?
这个问题有两个部分:
我将分别回答这两个问题。
如何验证多个字段?
Django REST Framework允许您通过覆盖validate
序列化程序上的方法来验证多个字段。在所有其他验证器都运行之后,最后完成此操作,并且文档中对此进行了详细说明。
def validate(self, attrs):
if "type" in attrs:
the_type = attrs["type"]
if the_type == "A":
# Check if "a_field" was actually passed
if "a_field" not in attrs:
raise ValidationError({"a_field": self.error_messages["required"]})
# Check that it's "great"
if attrs["a_field"] != "great":
raise Va class DemoSerializer(serializers.Serializer):
type = serializers.ChoiceField(choices=types)
a_field = serializers.CharField(required=False)
def to_representation(self, instance):
optional_fields = {
"B": ["a_field"],
}
data = super(DemoSerializer, self).to_representation(instance)
instance_type = data["type"]
if instance_type in optional_fields:
remove_fields = optional_fields[instance_type]
for field in remove_fields:
if field in data:
data.pop(field)
return datalidationError({"a_field": self.error_messages["not_great"]})
return attrs
这只会验证a_field
是否type
为"A"
。
如何仅验证某些输入的字段子集?
这是棘手的部分,因为默认情况下,Django REST Framework不会通过序列号中没有密钥的序列化器传递数据fields
。因此,如果在我们的示例中,您没有添加a_field
到列表中,则即使传入了数据,也总是会触发一个错误,要求您输入该字段。这意味着您需要将所有可选字段添加到您的列表中序列化器并将其标记为required=False
。
class DemoSerializer(serializers.Serializer):
type = serializers.ChoiceField(choices=types)
a_field = serializers.CharField(required=False)
不幸的是,使用序列化程序对数据进行序列化时,所有这些可选字段都显示出来,这是一个不幸的副作用,但是您可以通过重写来解决此问题to_representation
。您将需要提前知道要删除哪些字段。
class DemoSerializer(serializers.Serializer):
type = serializers.ChoiceField(choices=types)
a_field = serializers.CharField(required=False)
def to_representation(self, instance):
optional_fields = {
"B": ["a_field"],
}
data = super(DemoSerializer, self).to_representation(instance)
instance_type = data["type"]
if instance_type in optional_fields:
remove_fields = optional_fields[instance_type]
for field in remove_fields:
if field in data:
data.pop(field)
return data
这应该允许您根据返回的类型删除字段列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句