响应CreateAPIView DRF

时间:2019-03-01 10:01:49

标签: django django-rest-framework

我想要对CreateAPIView的响应,例如返回

Response(
            {
                'status': status_code.HTTP_200_OK,
                'message': 'Testimonials fetched',
                'data': serializer.data
             },)

但是我不知道哪种功能最适合在AddAPIView内使用以获得如上所述的响应

class AddAPIView(generics.CreateAPIView):
    queryset = Masjid.objects.all()
    serializer_class = serializers.MasjidAddSerialzer
    permission_classes = [IsAuthenticated]

1 个答案:

答案 0 :(得分:3)

覆盖 create() 视图类的 AddAPIView 方法

class AddAPIView(generics.CreateAPIView):
        queryset = Masjid.objects.all()
        serializer_class = serializers.MasjidAddSerialzer
        permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        return Response({
            'status': 200,
            'message': 'Testimonials fetched',
            'data': response.data
        })