1

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

3
  • have you tried to override the validate method of ParentSerializer ? Commented Dec 3, 2019 at 18:18
  • Yes, the values of the child are not surfaced with validate on the parent Commented Dec 3, 2019 at 18:21
  • can you add the validate method that you have tried? Commented Dec 3, 2019 at 18:30

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

your_condition is something should fetch from the input data
valid one. IMHO, it's better to implement validation logic inside the validators or something similar

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.