[英]Validate across nested serializers with django rest framework
If you were to have a nested serializer, but required a certain parameter in the parent depending on a value in the child, how could you enforce the logical requirement when necessary?如果你有一个嵌套的序列化器,但需要父级中的某个参数取决于子级中的值,你如何在必要时强制执行逻辑要求?
For example:例如:
class ChildSerializer(serializers.ModelSerializer):
foobar_attribute = serializers.ChoiceField(
required=True,
choices=foobar_choices,
)
class ParentSerializer(serializers.ModelSerializer):
child = ChildSerializer(required=True)
optional_attribute = serializers.CharField(
required=False,
)
optional_attribute
should be required only when foobar_attribute
is a certain choice, but optional for all else. optional_attribute
只有当应要求foobar_attribute
是必然选择,但可选的一切。 Throwing a validate
function on ParentSerializer
or ChildSerializer
only exposes attributes for that serializer, and none else.在
ParentSerializer
或ChildSerializer
上抛出validate
函数只公开该序列化程序的属性, ChildSerializer
公开其他属性。
How can I perform validation across nested serializers without creating rows ( as would occur if validation was performed in perform_create
)?如何在不创建行的情况下跨嵌套序列化程序执行验证(如果在
perform_create
中执行验证会发生这种情况)?
You can overwrite the __init__
function您可以覆盖
__init__
函数
def __init__(self, instance=None, *args, **kwargs):
super().__init__(instance, *args, **kwargs)
if your_condition:
self.fields['optional_attribute'].required = True
You can also change any attribute of the optional_attribute
field您还可以更改
optional_attribute
字段的任何属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.