Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PresentablePrimaryKeyRelatedField creates issue in redoc documentation. #180

Open
techlearner96 opened this issue Jun 17, 2022 · 2 comments

Comments

@techlearner96
Copy link

I have a serializer field which works differently for read and write. I used PresentablePrimaryKeyRelatedField for that.
e.g:
car_type = PresentablePrimaryKeyRelatedField(
queryset=CarType.objects.all(),
presentation_serializer=CarTypeSerializer,
read_source=None
)
This works well when accessing the api, like in request i give an integer value to car_type field and in response it gives a dictionary to car_type field. Api request-response thing worked well.
Issue is with swagger documentation. In documentation, it gives car_type as integer field in both request and response schema.
How can i deal with that?

@gokselcoban
Copy link

AFAIK, there is no solution for this right now. It needs to be improved.

If you are using drf-spectacular, PolymorphicProxySerializer may help. It allows you to show different serializers depending on the situation. You may define an input and output serializer and represent them differently.

Something like that:

# input/accept
car_type = PrimaryKeyRelatedField(
    queryset=CarType.objects.all(),
)

# output/response
car_type = CarTypeSerializer()

https://drf-spectacular.readthedocs.io/en/latest/drf_spectacular.html#drf_spectacular.utils.PolymorphicProxySerializer
https://drf-spectacular.readthedocs.io/en/latest/drf_spectacular.html?highlight=PolymorphicProxySerializer#drf_spectacular.utils.PolymorphicProxySerializer

@ckarli
Copy link

ckarli commented Oct 25, 2022

You can use OpenApiSerializerFieldExtension

from drf_extra_fields.relations import PresentablePrimaryKeyRelatedField
from drf_spectacular.extensions import OpenApiSerializerFieldExtension
from drf_spectacular.settings import spectacular_settings

class PresentablePrimaryKeyRelatedFieldSchemaExtension(OpenApiSerializerFieldExtension):
    target_class = PresentablePrimaryKeyRelatedField

    def map_serializer_field(self, auto_schema, direction):
        if direction == "response" and spectacular_settings.COMPONENT_SPLIT_REQUEST:
            return auto_schema._map_serializer_field(
                self.target.presentation_serializer, direction, bypass_extensions=True
            )
        else:
            return auto_schema._map_serializer_field(
                self.target, direction, bypass_extensions=True
            )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants