0

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!

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

I believe this should be obj.group.group_name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.