简体   繁体   中英

drf action views with similar url_path not showing on drf swagger

I have two action views with same url_path ('favorite') but different methods to handle retrieving and deletion of an object. Only one of these action views is mapped and show on swagger API (using drf-yasg).

from django.utils.decorators import method_decorator
from drf_yasg.utils import no_body, swagger_auto_schema
from rest_framework.decorators import action
from rest_framework.mixins import ListModelMixin
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.status import (HTTP_201_CREATED,
                                HTTP_204_NO_CONTENT,
                                HTTP_404_NOT_FOUND,
                                HTTP_200_OK
                                )
from rest_framework.viewsets import GenericViewSet

from housery.house.models import House
from utils.drf_params import app_id
from utils.mixins import FilterQueryByHouse

from .serializers import HouseSerializer


@method_decorator(name="list", decorator=swagger_auto_schema(
    manual_parameters=[app_id]
    ))
class HouseViewSet(FilterQueryByHouse, ListModelMixin, GenericViewSet):
    queryset = House.objects.filter().prefetch_related(
        "opening_hours", "special_opening_hours__opening_hours",
    )
    serializer_class = HouseSerializer

    def get_permissions(self):
        if self.action in ["list"]:
            return [AllowAny()]
        return [IsAuthenticated()]

    @action(methods=["get"], detail=True, url_path="favorite", url_name="favorite-read")
    def retrieve_favorite(self, request):
        """Retrieve favorite house"""
        if request.user.favorite_house_id:
            instance = request.user.favorite_house
            Response(self.get_serializer(instance=instance).data, status=HTTP_200_OK)
        return Response(status=HTTP_404_NOT_FOUND)

    @action(methods=["delete"], detail=False, url_path="favorite", url_name="favorite-remove")
    def unset_favorite(self, request):
        """Remove favorite house"""
        request.user.favorite_house = None
        request.user.save()
        return Response(status=HTTP_204_NO_CONTENT)

    @swagger_auto_schema(request_body=no_body)
    @action(methods=["post"], detail=True)
    def favorite(self, request, pk):
        """set given house id as favorite house"""
        instance = self.get_object()
        request.user.favorite_house = instance
        request.user.save()
        return Response(self.get_serializer(instance=instance).data, status=HTTP_201_CREATED)

在此处输入图片说明

I would only get either "get" (retrieve_favorite) or "delete" (unset_favorite), but not both. I am sure I am doing some stupid that I could not yet have picked up on, and I would appreciate any help.

Maybe that would work ?

https://www.django-rest-framework.org/api-guide/viewsets/#routing-additional-http-methods-for-extra-actions

...
class HouseViewSet(FilterQueryByHouse, ListModelMixin, GenericViewSet):
    queryset = House.objects.filter().prefetch_related(
        "opening_hours", "special_opening_hours__opening_hours",
    )
    serializer_class = HouseSerializer

    def get_permissions(self):
        if self.action in ["list"]:
            return [AllowAny()]
        return [IsAuthenticated()]

    @action(methods=["get"], detail=True, url_path="favorite", url_name="favorite-detail")
    def favorite_detail(self, request, *args, **kwargs):
        """Retrieve favorite house"""
        if request.user.favorite_house_id:
            instance = request.user.favorite_house
            Response(self.get_serializer(instance=instance).data, status=HTTP_200_OK)
        return Response(status=HTTP_404_NOT_FOUND)

    @favorite_detail.mapping.delete
    def unset_favorite(self, request, *args, **kwargs):
        """Remove favorite house"""
        request.user.favorite_house = None
        request.user.save()
        return Response(status=HTTP_204_NO_CONTENT)

    @swagger_auto_schema(request_body=no_body)
    @action(methods=["post"], detail=True)
    def favorite(self, request, pk):
        """set given house id as favorite house"""
        instance = self.get_object()
        request.user.favorite_house = instance
        request.user.save()
        return Response(self.get_serializer(instance=instance).data, status=HTTP_201_CREATED)

I think that new viewset for handling favorites would be better solution for this situation - it's cleaner.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM