django-json-api / django-rest-framework-json-api

JSON:API support for Django REST framework
https://django-rest-framework-json-api.readthedocs.org/
BSD 2-Clause "Simplified" License
1.18k stars 294 forks source link

JSONRenderer does not extract includes from PolymorphicModelSerializer properly #1191

Closed dmuseychuk-invgate closed 9 months ago

dmuseychuk-invgate commented 9 months ago

When using PolymorphicModelSerializer with JSONRenderer, the extract_included method is retrieving the base polymorphic serializer instead of the specific serializer corresponding to the object instance. This results in the includes not being processed correctly, as the base polymorphic serializer is not equipped to handle the specifics of each derived instance.

It appears that the issue can be resolved by modifying the render method to correctly identify and use the appropriate serializer based on the object instance during the rendering process. This adjustment should enable includes to function as expected with polymorphic serializers.

if serializer is not None:
    # Extract root meta for any type of serializer
    json_api_meta.update(self.extract_root_meta(serializer, serializer_data))
    if getattr(serializer, "many", False):
        ...
    else:
        if isinstance(serializer, PolymorphicModelSerializer):
            resource_instance = serializer.instance
            serializer_class = serializer.get_polymorphic_serializer_for_instance(resource_instance)
            serializer = serializer_class(resource_instance, context=serializer.context)

            fields = utils.get_serializer_fields(serializer)
            ...
sliverc commented 9 months ago

This seems to be a double post, so closing this in favor of #1190.