0

I'm still pretty new to creating views in Django Rest Framework, I can make basic views but I still have no clue about definitions so please help me out here.

I've got this View which gets the answers of a question (by a given question id). The list definition works perfectly, however I want to make a delete_all function which deletes these results. You can see what I came up with below.

URL

router.register('manager/course/question/answers', QuestionAnswerView)


http://.../manager/course/question/answers/5 works.
http://.../manager/course/question/answers/delete_all/5 does not work.

View

class QuestionAnswerView(viewsets.ModelViewSet):
    queryset = QuestionAnswer.objects.all()
    serializer_class = QuestionAnswerSerializer

    # works
    def list(self, request):
        queryset = QuestionAnswer.objects.all()
        if request.query_params:
            question_id = request.query_params['question_id']
            queryset = QuestionAnswer.objects.filter(question=question_id)
        serializer = QuestionAnswerSerializer(queryset, many=True)
        return Response(serializer.data)
    
    # does not work
    def delete_all(self, request):
        if request.query_params:
            question_id = request.query_params['question_id']
            queryset = QuestionAnswer.objects.filter(question=question_id)
            queryset.delete()
        return Response('success')
SJ19
  • 1,933
  • 6
  • 35
  • 68

1 Answers1

0

This is all explained in the documentation:

The ModelViewSet class inherits from GenericAPIView and includes implementations for various actions, by mixing in the behavior of the various mixin classes. The actions provided by the ModelViewSet class are .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy().

So there is no delete_all(). You will have to tell the viewset and the router to make it available:

If you have ad-hoc methods that should be routable, you can mark them as such with the @action decorator.