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

Pydantic model in responses is overwritten by request serializer #1369

Open
araggohnxd opened this issue Jan 21, 2025 · 0 comments
Open

Pydantic model in responses is overwritten by request serializer #1369

araggohnxd opened this issue Jan 21, 2025 · 0 comments

Comments

@araggohnxd
Copy link

araggohnxd commented Jan 21, 2025

Describe the bug
When declaring a DRF view decorated with @extend_schema, if the responses argument is a Pydantic model and the request argument is a DRF serializer, the response payload will be overwritten by that of the request serializer, both in Swagger and Redoc UI.

While testing to reproduce, I figured that it has something to do with the naming of the model and serializer. In the example below, if MyModel is renamed to something like MyPydanticModel, or something else that doesn't overlap with the initial portion of the serializer name MyModelSerializer, it seems to work properly.

To Reproduce

from rest_framework import serializers, views
from rest_framework.response import Response
from rest_framework.request import Request
from pydantic import BaseModel
from drf_spectacular.utils import extend_schema


class MyModelSerializer(serializers.Serializer):
    field1 = serializers.CharField()
    field2 = serializers.IntegerField()


class MyModel(BaseModel):
    other_field1: str
    other_field2: int


@extend_schema(
    request=MyModelSerializer,
    responses=MyModel,
)
class MyView(views.APIView):
    def post(self, request: Request):
        serializer = MyModelSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        response = MyModel(
            other_field1=serializer.validated_data['field1'],
            other_field2=serializer.validated_data['field2'],
        )

        return Response(response.model_dump())

Image

Expected behavior
Image

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

1 participant