[Answered ]-Serialize custom field from an object in a list using the Django Rest Framework

1👍

It sounds like you are looking for a SlugRelatedField instead of a nested serializer.

class FooSerializer(models.ModelSerializer):
    bars = serializers.SlugRelatedField(slug_field='bar_text')

1👍

A solution that nearly works for me is to override the bars attribute on the FooSerializer with a BarSerializer:

class FooSerializer(models.ModelSerializer):
    bars = BarSerializer(many=True)

However, this gives me the following when serialized:

{
    bars: [
        {
            'bar_text' : 'baz',
        },
        { 
            'bar_text' : 'whizz'
        }
    ]
}

Which is fine, but I really want a list of bar_texts rather than key/value pairs. What’s more, if I add more fields to Bar that I do not want to be serialized into Foo, I have no control over which are displayed here vs. a pure serialization of Bar. If I don’t get a better solution I’ll accept this shortly.

Leave a comment