1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Django REST Framework】swaggerにPageNumberPaginationのレスポンスが表示させる(力技)

Last updated at Posted at 2024-10-30

前置き

初学者なりの知らなかったというお話なので、多くの方には関係のない内容です。

問題

実際に返却されるレスポンスは問題ないけど、swaggerにページネーション形式のレスポンスが表示されない

@extend_schema(responses=SongListSerializer, tags=["song"])
class SongListView(views.APIView):
    pagination_class = CustomPaginator

    def get(self: Self, request: Request, *args: Any, **kwargs: Any) -> Response:
        """曲一覧情報の取得"""
        songs = Song.objects.alive().select_related("album", "artist").all()
        paginator = CustomPaginator()
        result_page = paginator.paginate_queryset(songs, request)
        serializer = SongListSerializer(data=result_page, many=True)
        serializer.is_valid()
        return paginator.get_paginated_response(serializer.data)

あれ。。

スクリーンショット 2024-10-30 23.16.32.png

実際にリクエストを送るとページネーション形式のレスポンスが返る
スクリーンショット 2024-10-30 23.18.19.png

解決

from drf_spectacular.utils import extend_schema, inline_serializer
@extend_schema(
    responses={
        200: inline_serializer(
            name="PaginatedSongResponse",
            fields={
                "count": serializers.IntegerField(),
                "next": serializers.CharField(allow_null=True),
                "previous": serializers.CharField(allow_null=True),
                "results": SongListSerializer(many=True),
            },
        ),
    },
    tags=["song"],
)
class SongListView(views.APIView):
    pagination_class = CustomPaginator

    def get(self: Self, request: Request, *args: Any, **kwargs: Any) -> Response:
        """曲一覧情報の取得"""
        songs = Song.objects.alive().select_related("album", "artist").all()
        paginator = CustomPaginator()
        result_page = paginator.paginate_queryset(songs, request)
        serializer = SongListSerializer(data=result_page, many=True)
        serializer.is_valid()
        return paginator.get_paginated_response(serializer.data)

image.png

えぇ。。。。

こんなデコレータ書かないといけないんですか。。。

なにかいい方法はないものでしょうか?

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?