Get object by field other than primary key

前端 未结 5 1034
眼角桃花
眼角桃花 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:24

    What about a solution just like this:

    views.py

    class VideoDetailView(generics.RetrieveAPIView):
        serializer_class = VideosSerializer
        lookup_field = 'videoName'
    

    reasoning: you want a detailview, so there is no need for ListView but RetriveAPIView

    if some furthere manipulation will be needed just override get_object method like this:

    def get_object(self):
        obj = super(VideoDetailView, self).get_object()
        # perform some extra checks on obj, e.g custom permissions
        return obj
    

提交回复
热议问题