简体   繁体   中英

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. Throwing a validate function on ParentSerializer or ChildSerializer only exposes attributes for that serializer, and none else.

How can I perform validation across nested serializers without creating rows ( as would occur if validation was performed in perform_create )?

You can overwrite the __init__ function

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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