Search code examples
django-rest-framework

How to add arbitrary data to validated_data of django rest serializer object?


I want to add additional field-value pairs to the serializer's validated data object after the is_valid() operations are done. How can I do that?


Solution

  • A better approach would be to define a hidden field say, my_hidden_field = serializer.HiddenField(default=None) in the Serializer class whose value can be obtained in following ways:

    • Passed during instance creation, eg. `serializer = MySerializer(my_hidden_field=val)
    • Define a validate_my_hidden_field for it and derive its value based on context.
    • If its value depends on other fields, then use validate method to derive its value and assign to it.