正确的写法:
class CategoriesView(generics.ListCreateAPIView):
queryset = Category.objects.all()
serializer_class = CategorySerializers
permission_classes = (IsAuthenticated,)
def create(self, request, *args, **kwargs):
if self.queryset.filter(category=request.data.get("category").upper()).exists():
return Response(status=status.HTTP_201_CREATED)
return super(CategoriesView, self).create(request, *args, **kwargs)
下面的这种写法:
class CategoriesView(generics.ListCreateAPIView):
queryset = Category.objects.all()
serializer_class = CategorySerializers
permission_classes = (IsAuthenticated,)
def post(self, request, *args, **kwargs):
if self.queryset.filter(category=request.data.get("category").upper()).exists():
return Response(status=status.HTTP_201_CREATED)
return super(CategoriesView, self).create(request, *args, **kwargs)
会出现serializer = self.get_serializer(data=request.data)
报错,提示说request
不存在data
属性。request
参数在post
中时正常的,但是在调用super(CategoriesView, self).create(request, *args, **kwargs)
时,request
参数的外面,django
再次包裹了一次request
,所以导致data
属性不存在。