如何在request.data中更改django rest框架中的serializer validataion?

时间:2017-07-17 21:29:47

标签: django django-rest-framework

所以我正在制作具有以下结构的测验应用

class UserQuizRecord(models.Model):
    user = models.OneToOneField(User)
    quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='userrecord')
    score = models.FloatField(default=0.00)

我有序列化程序类

class UserQuizRecordSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserQuizRecord
        fields = ('user', 'quiz','score')

这是views.py文件和我提供的数据{quiz:1,score:7}的详细路径我希望将用户添加到views函数中的request.data或serializer。我没有找到正确的方法。

class QuizView(viewsets.ModelViewSet):
    serializer_class = QuizSerializer
    queryset = Quiz.objects.all()
    model = Quiz

    @detail_route(methods=['post'], permission_classes=[AllowAny], url_path='rank')
    def rank(self, request, pk=None):
        request.data.quiz = Quiz.objects.get(pk=pk)
        serializer = UserQuizRecordSerializer(data = request.data )
        if serializer.is_valid():
            serializer.save()
            rank = UserQuizRecord.objects.filter(Q(quiz=request.data.quiz.id),Q(score__gte=request.data.score)).count()
            return Response({'rank':rank}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)  

执行此操作的最佳方法是什么?

0 个答案:

没有答案