Get object by field other than primary key

前端 未结 5 1045
眼角桃花
眼角桃花 2020-12-30 09:52

Hi I\'m new to both Django and the Django-Rest-Framework. I\'ve gone through the tutorials. What I\'m trying to do (as a learning exercise) is return an object based off a f

5条回答
  •  暖寄归人
    2020-12-30 10:04

    Using ModelViewSets you can use @action decorator you can define specific method if you don't want to change the complete lookup behavior of the viewset and serializer. For example:

    class VideoDetailView(viewsets.ModelViewSet):
        queryset = Videos.objects.all()
        serializer_class = VideosSerializer
    
        @action(detail=True)
        def video_name(self, request, pk=None):
            queryset = Video.objects.get(videoName=pk) # pk will be the video name
            serializer = VideosSerializer(queryset, many=True) # You can specify other serializer if you want here
            return Response(serializer.data)
    

    Then, your url will be: myserver:8000/videos/SecondVideo/video_name/

    You can read more in: https://www.django-rest-framework.org/api-guide/viewsets/

提交回复
热议问题