2

I am using Django REST Framework. I have a parent serializer class like so:

class MyParentSerializer(serializers.Serializer):

  # Use custom serializer as a field.
  my_field = MyFieldSerializer(
      required=False,
  )

  name = serializers.Charfield()
}

  def validate(data):
    # validation logic

And then my child serializer that is used above looks like this:

class MyFieldSerializer(serializers.Serializer):

    email_address = serializers.ListField(
        required=False,
        child=serializers.CharField(),
    )

    phone_number = serializers.ListField(
        required=False,
    )

    def validate(self, data):
        data <-- <-- This is empty if I pass in random invalid data!
        check_for_undefined_fields(self.data, self.fields)
        return data

Now, I pass the following data:

{
  "my_field": { "invalid_field": "foo"},
  "name": "bar"
}

However, if I check data in the validate method in my MyFieldSerializer class during validation, IT'S EMPTY!

Why? How can I fix this so that data is actually the data I passed?

3 Answers 3

2

Only fields which you have declared will be available in validate or is_valid or create methods. If you need to access those fields, you can use self.initial_data.

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

2 Comments

So how do I make sure that no undefined fields are passed in my child serializer?
You will have to do this in your parent serializer validate method.
2

You are not using ModelSerializer so every field in request have to be added in Serializer. In you case you just have to define invalid_field

  class MyFieldSerializer(serializers.Serializer):

    email_address = serializers.ListField(
        required=False,
        child=serializers.CharField(),
    )

    phone_number = serializers.ListField(
        required=False,
    )
    invalid_field = serializers.CharField()

    def validate(self, data):
        data <-- <-- This is empty if I pass in random invalid data!
        check_for_undefined_fields(self.data, self.fields)
        return data

1 Comment

But this means if I pass invalid_field it will work but if I pass invalid_field_foo or any other string then it wont work. Which is what I want it to validate -> If any field other than the ones defined is encountered then throw an error,
0

In the nested serializer, you might be writing the nested field in create which you have set to read_only=True. Change that to read_only=False will solve the problem.

For e.g: question_response = QuestionResponseSerializer(many=True, read_only=True)

Change this to: question_response = QuestionResponseSerializer(many=True, read_only=False)

Comments

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.