在django rest泛型CreateAPIView中覆盖create方法

时间:2017-08-31 12:48:31

标签: python django django-rest-framework django-generic-views

我的django app的views.py如下,

class MemberCreate(generics.CreateAPIView):
    queryset = members.objects.all()
    serializer_class = MemberSerializer
    permission_classes = (permissions.IsAdminUser,)

    def create(self, serializer):
        ''' I wanted to do some stuff with serializer.data here '''
        pass 

在上面的内容中如果我覆盖了create函数,则返回失败并出现以下错误,即使我没有做任何事情,只是写入传递它失败了,

AssertionError: Expected a `Response`, `HttpResponse` or `HttpStreamingResponse` to be returned from the view, but received a `<class 'NoneType'>`

2 个答案:

答案 0 :(得分:5)

返回时间应为instanceof Response。您可以在parent

之后返回stuff课程回复
def create(self, request, *args, **kwargs):
    ''' I wanted to do some stuff with serializer.data here '''
    return super(MemberCreate, self).create(request, *args, **kwargs)

或者如果您不想要父回复,那么只需返回Response个实例

def create(self, request, *args, **kwargs):
    ''' I wanted to do some stuff with serializer.data here '''
    return Response(status=204)

答案 1 :(得分:1)

您的视图应返回Response对象,如AssertionError堆栈跟踪中所述。

在您的情况下,您可以尝试返回空的Response以测试您的观看次数和serializer.data

from rest_framework.response import Response
from rest_framework import status


class MemberCreate(generics.CreateAPIView):
    queryset = members.objects.all()
    serializer_class = MemberSerializer
    permission_classes = (permissions.IsAdminUser,)

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(...)
        data = serializer.data

        # ...

        return Response(status=status.HTTP_204_NO_CONTENT)

通常,您希望最后返回serializer.validated_data,因此此行可能如下所示:

return Response(serializer.validated_data, status=status.HTTP_201_CREATED)