我正在尝试将django视图转换为APIView,这是正常视图,下面是我尝试过的视图。

Django视图

@method_decorator([login_required, teacher_required], name='dispatch')
class QuizResultsView(DetailView):
    model = Quiz
    context_object_name = 'quiz'
    template_name = 'classroom/teachers/quiz_results.html'

    def get_context_data (self, **kwargs):
        quiz = self.get_object()

        if (quiz.status == 'Assigned'):

            """Some Code"""

            cursor = connection.cursor()


            def dictfetchall (cursor):
                desc = cursor.description
                return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]

            """ Some More Code """

            extra_context = {'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes,
                             'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids,
                             'driver_num': driver_num, 'lat_lon_orig': lat_lon_orig, 'lat_lon_dest': lat_lon_dest,
                             'user_pass': user_pass, 'username': username, 'password': password, }


            kwargs.update(extra_context)


            return super().get_context_data(**kwargs)


        else:

            cursor = connection.cursor()

            def dictfetchall (cursor):
                desc = cursor.description
                return [dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall()]

            cursor.execute('''SELECT STATEMENT''', [quiz.id])

        """ Some More Code """


            extra_context = {'taken_quizzes': taken_quizzes, 'total_taken_quizzes': total_taken_quizzes,
                             'quiz_score': quiz_score, 'least_bid': least_bid, 'matching_bids': matching_bids}
            kwargs.update(extra_context)

            return super().get_context_data(**kwargs)

    def get_queryset (self):
        return self.request.user.quizzes.all()


根据documentation我添加:

REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': [
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ]
}


在我的settings.py中,我使用的是return super().get_context_data(**kwargs)而不是return Response(extra_content),但它似乎不起作用。我做错了什么事?

请帮忙!!

最佳答案

作为documentation


  以下设置控制基本的API策略,并应用于每个基于APIView类的视图或基于@api_view函数的视图。


意味着,您所做的更改将反映在APIViewAPIView的子类中,而不反映在DetailView或任何Django CBV中。

您可以像这样简单地将视图转换为APIView

@method_decorator([login_required, teacher_required], name='dispatch')
class QuizResultsView(APIView):
    def get_object(self, pk):
        try:
            return Snippet.objects.get(pk=pk)
        except Snippet.DoesNotExist:
            raise Http404

    def get(self, request, pk, format=None):
          quiz = self.get_object(pk)
          # --- rest of the code ---
          return Response(extra_content)


但是我建议使用GenericViewRetrieveAPIView,并使用serializer序列化数据。

10-04 21:00