Skip to content

Metadata on PolymorphicModelSerializer #706

Open
@Ardillen66

Description

@Ardillen66

PolymorphicModelSerializer does not implement get_root_meta() to populate the meta key of the response JSON.
This might be by design, but it took me some time to figure this out and implement this method to delegate to the appropriate serializer. I implemented get_root_meta() on the serializer that is extending PolymorphicModelSerializer in a similar way to get_fields().
The code:

class MySerializer(serializers.PolymorphicModelSerializer):

    def get_root_meta(self, resource, many):
        if self.instance not in (None, []):
            if not isinstance(self.instance, QuerySet):
                serializer_class = self.get_polymorphic_serializer_for_instance(self.instance)
                return serializer_class(self.instance, context=self.context).get_root_meta(resource, many)
            else:
                raise Exception("Cannot get metadata from a polymorphic serializer given a queryset")
        return {}

Not sure if this would be the way to imlpement it on PolymorphicModelSerializer, but it works for me.
I think it would be nice if this is provided by default, or the documentation mentions that you need to implement it yourself when using PolymorphicModelSerializer.

p.s. First time posting an issue, so let me know if something is not clear or I missed something.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions