Arial
Arial

Reputation: 5054

How to pull nested fields out when serializing -- Django Rest Framework

I have a serialized model that looks something like below:

{
    name: "...."
    section: [
        {
            section_name: "..."
            group:[
                {"group_name": "..."}
            ]
        },
    ]
}

Is there any way I can pull out group_name under Django Rest Framework such that:

{
    name: "...."
    section: [
        { section_name: "..."},
    ]
    group_name:[
        { group_name: "..." }
    ]
}

The reason why I want to do so is such that I can use django filter to filter on group_name.

For some reason, I couldn't seem to make RelatedFilter work under django rest framework filter (third party package: https://github.com/philipn/django-rest-framework-filters/blob/master/rest_framework_filters/filters.py), and am looking a workaround for this.

Would love to hear any better ways to approach this problem.

Thank you in advance!

Upvotes: 0

Views: 570

Answers (2)

Mark Galloway
Mark Galloway

Reputation: 4151

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.

Upvotes: 1

zymud
zymud

Reputation: 2249

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

Upvotes: 0

Related Questions