Search code examples
djangodjango-rest-frameworkdjango-serializer

Django rest framework Serializer: get source from POST request


I want to add data from a POST request to my serializer:

class DeviceSerializer(ModelSerializerWithFields):
    class Meta:
        model = Device
        exclude = ("groups",)

    last_values = serializers.JSONField(source="get_graph_data", read_only=True)

How can I get the resulting values from passing a specific request to get_graph_data?

Ideally something like:

last_values = serializers.JSONField(source="get_graph_data", read_only=True, payload="{'foo':1, 'bar':15}")

but if not, at least a way to pass one value so I can edit the endpoint to take this specific case into account


Solution

    1. Include the information you want to pass to the serializer in the serializers context

    2. Use a SerializerMethodField() for your last_values field and call the method get_graph_data there with your payload.