我使用DJango REST Framework模块在DJango工作。
对于我制作的每个模型,我都有一个观点:
class CustomAPIView(APIView):
renderer_classes = (JSONRenderer, )
permission_classes = (IsAuthenticated, )
@csrf_exempt
def post(self, request):
raw_data = serializers.SearchStateSerializer(data=request.data)
if raw_data.is_valid():
searched_data = serializers.ShowStateSerializer(data=serializers.State.objects.extra(where=raw_data.data['where'], order_by=raw_data.data['order_by']), many=True)
return JsonResponse(paginate_data(searched_data=searched_data, request_data=raw_data), status=status.HTTP_202_ACCEPTED)
else:
return JsonResponse(raw_data.errors, status=status.HTTP_400_BAD_REQUEST)
在此代码中,有3个约束发生变化:
所以我想创建一个抽象,其中我只指定这3个东西并且视图有效。我怎样才能做到这一点?我搜索了很多但没有运气。必须提供这3个约束,否则会引发错误。
答案 0 :(得分:2)
将此作为您的父类使用:
class CustomAPIView(APIView):
renderer_classes = (JSONRenderer, )
permission_classes = (IsAuthenticated, )
search_state_serializer_class = None
show_state_serializer_class = None
state_model = None
@csrf_exempt
def post(self, request):
raw_data = self.search_state_serializer_class(data=request.data)
if raw_data.is_valid():
searched_data = self.show_state_serializer_class(
data=(self.state_model.objects
.extra(where=raw_data.data['where'],
order_by=raw_data.data['order_by'])),
many=True)
return JsonResponse(paginate_data(searched_data=searched_data, request_data=raw_data), status=status.HTTP_202_ACCEPTED)
else:
return JsonResponse(raw_data.errors, status=status.HTTP_400_BAD_REQUEST)
现在你可以简单地为类字段提供值,post方法也可以。
class MyView(CustomApiView):
search_state_serializer_class = MySearchStateSerializer
show_state_serializer_class = MyShowStateSerializer
state_model = MyStateModel