[Fixed]-How to pull nested fields out when serializing โ€” Django Rest Framework

1๐Ÿ‘

You can use the source attribute of a serializer field to bring related object fields to the top level.

class MySerializer(serializers.ModelSerializer):
    group_name = serializers.CharField(source='section.group.group_name')

    class Meta:
        model = MyModel
        fields = ('group_name',)

However, this does not remove the performance implications of fetching related objects so select_related and prefetch_related on your queryset are still needed for optimal performance.

๐Ÿ‘คMark Galloway

0๐Ÿ‘

Filter is related to model, not its serializer version, so even if you will create field group_name in serializer output โ€“ it will not help with filtering. So actually I recommend you to post question about RelatedFilter.

Answer to your question:

You can use SerializerMethodField to add custom field to object representation.

class MyModelSerializer(serializers.ModelSerializer):
    group_name = serializers.SerializerMethodField()

    class Meta:
        model = MyModel

    def get_group_name(self, obj):
        return obj.group_name
๐Ÿ‘คzymud

Leave a comment