arshbot
arshbot

Reputation: 15795

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 )?

Upvotes: 1

Views: 445

Answers (1)

Ignacio Villela
Ignacio Villela

Reputation: 150

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

Upvotes: 1

Related Questions