我对在 Django Rest Framework 中创建视图仍然很陌生,我可以制作基本视图,但我仍然不知道定义,所以请在这里帮助我。
我有这个 View 可以得到问题的答案(通过给定的问题 ID)。列表定义完美运行,但是我想创建一个删除这些结果的 delete_all 函数。你可以在下面看到我想出的。
网址
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.
看法
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')