未定义全局名称“get_serializer_class”

时间:2014-09-15 02:30:44

标签: python django django-rest-framework

我知道我需要导入它,但我从哪里导入它?

from rest_framework import get_serializer_class

以上内容并不起作用,我在文档中没有看到任何可以解释函数导入位置的内容。

作为参考,我认为这是错误的 -

class CalendarDetailView(generics.RetrieveUpdateDestroyAPIView):
    def get_serializer_class(self):
        if self.request.method == 'GET':
            serializer_class = CalendarGETSerializer
        elif self.request.method == 'PUT':
            serializer_class = CalendarPUTSerializer
        return serializer_class

    def get(self, request, format=None):
        evntname = self.request.GET.get('name')
        queryset = Evntmst.objects.filter(evntmst_name=evntname)
        serializer = get_serializer_class(queryset)
        if queryset:
            return Response(serializer.data)
        else:
            raise Http404

    def put(self, request, format=None):
        serializer = get_serializer_class(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

编辑 - 这是Traceback

Traceback:
File "D:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  112.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "D:\Python27\lib\site-packages\django\views\generic\base.py" in view
  69.             return self.dispatch(request, *args, **kwargs)
File "D:\Python27\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view
  57.         return view_func(*args, **kwargs)
File "D:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
  400.             response = self.handle_exception(exc)
File "D:\Python27\lib\site-packages\rest_framework\views.py" in dispatch
  397.             response = handler(request, *args, **kwargs)
File "D:\Tidal\API\views.py" in get
  398.         serializer = get_serializer_class(queryset)

Exception Type: NameError at /deploy/calendartest/
Exception Value: global name 'get_serializer_class' is not defined

1 个答案:

答案 0 :(得分:3)

我需要查看堆栈跟踪以更好地了解错误的来源,但我相信您实际上并不需要导入任何内容。

从这些文档:http://www.django-rest-framework.org/api-guide/generic-views#get_serializer_classself

看起来你只需要在你定义为api的类中覆盖该方法。

你的api课程从我能看到的一目了然看起来很好

编辑:在看到追溯之后,它更加清晰:

你应该

self.get_serializer_class()(queryset)您目前有get_serializer_class(queryset)