Dmitrii Mikhailov
Dmitrii Mikhailov

Reputation: 5231

How can I embed two fields together in serializer

I have model like:

class MyModel:
    somefield = ...
    ...
    f_value = ...
    f_metric = ...

The question is: How can I embed these fields in serializer: so that the resulting serialized object would look like this:

{
"somefield": ...,
...,
"f": {"value": ..., "metric": ...}
}

Upvotes: 1

Views: 93

Answers (1)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41691

You can use a nested serializer to make this work.

class FSerializer(serializers.Serializer):
    value = serializers.Field(source="f_value")
    metric = serializers.Field(source="f_metric")

class MyModelSerializer(serializers.ModelSerializer):
    somefield = serializers.Field()

    f = FSerializer(source="*")

This should give you the nested output you are looking for. You can find more information on nesting serializers in the Django REST Framework documentation.

Upvotes: 2

Related Questions