简体   繁体   English

使用 django rest 框架跨嵌套序列化程序进行验证

[英]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.ParentSerializerChildSerializer上抛出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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM