在一个基于类的视图中是否可以有2个post方法?
我试图做这样的事情,但是当然不起作用
我的自定义视图:
class UserExamDetail(APIView):
def get_queryset(self, pk):
return Exam.objects.get(pk=pk)
def get(self, request, pk):
exam = self.get_queryset(pk=pk)
if exam:
exam_closed = 0
exam_opened = 0
c_questions = ClosedQuestion.objects.filter(exam=exam)
o_questions = OpenedQuestion.objects.filter(exam=exam)
for question in c_questions:
points = int(question.points)
exam_closed += points
for question in o_questions:
points = int(question.points)
exam_opened += points
exam.score = exam_closed + exam_opened
exam.save()
serializer = ExamCreatorSerializer(exam)
return Response(serializer.data)
def post(self, request, pk):
serializer = ClosedQuestionSerializer(data=request.data)
if serializer.is_valid():
serializer.save(exam=pk)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
def post(self, request, pk):
serializer = OpenedQuestionSerializer(data=request.data)
if serializer.is_valid():
serializer.save(exam=pk)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)
只有第一个post有效,并且例如当我尝试更改函数名称:post1和post 2时,Django不会将此方法识别为post。如果有可能这样做,那么我也很好奇我是否应该执行这种视图,或者Post方法应该是单独的视图?
答案 0 :(得分:3)
您可以将其他数据传递到请求正文,并确定要使用的序列化程序。这是一个例子。
def post(self, request, pk):
if request.POST.get('is_opened'):
serializer_class = OpenedQuestionSerializer
else:
serializer_class = ClosedQuestionSerializer
serializer = serializer_class(data=request.data)
if serializer.is_valid():
serializer.save(exam=pk)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.data, status=status.HTTP_400_BAD_REQUEST)