首页 > 解决方案 > 将发布请求保存到数据库后是否可以返回 GET 请求?

问题描述

在发出发布请求并将数据保存到数据库后,我一直在尝试返回 GET 响应。而不是将经过验证的序列化数据返回给 API 调用者。

为了简化。RN 通过发布请求返回的数据是经过序列化程序验证的响应以及 201 代码。

相反,我想返回如果在同一 URL 上发出获取请求会返回的内容。即 Pollquestion 序列化程序。

它将在前端节省另一个 GET 请求处理。

以下是序列化程序:

class PollVoteSerializer(serializers.ModelSerializer):

    class Meta:
        model = PollVote
        fields = '__all__'


class PollAnswerSerializer(serializers.ModelSerializer):

    is_correct_answer = serializers.SerializerMethodField()
    answer_votes = serializers.SerializerMethodField(read_only=True)

    class Meta:
        model = PollAnswer
        fields = ('id', 'answer', 'is_correct_answer', 'answer_votes', )

    def get_is_correct_answer(self, object):

        if object.question.is_finished:
            return object.is_correct

        return False

    def get_answer_votes(self, object):
        return object.answer_vote.count()


class PollQuestionSerializer(serializers.ModelSerializer):

    choices = PollAnswerSerializer(many=True, read_only=True)
    total_votes = serializers.SerializerMethodField(read_only=True)
    user_voted = serializers.SerializerMethodField(read_only = True)

    class Meta:
        model = PollQuestion
        fields = ['id', 'question_name', 'created_by',
                  'is_finished', 'total_votes','user_voted', 'choices', ]

    def get_total_votes(self, question_vote):
        c = PollVote.objects.filter(question=question_vote).count()
        return question_vote.question_vote.all().count()

    def get_user_voted(self, object):
        user_id = self.context['request'].user.id    
        return PollVote.objects.filter(question__id = object.id, voted_by = user_id).exists()

这是视图。

class GetPoll(viewsets.ModelViewSet):
    
    def get_serializer_class(self):
        if self.action == 'create':
            return PollVoteSerializer
        else:
            return PollQuestionSerializer
            
    queryset = PollQuestion.objects.all().order_by('-id')
    authentication_classes = (authentication.TokenAuthentication,)
    permission_classes = [IsAuthenticated]
    pagination_class = StandardResultsSetPagination

为大量不整洁的格式道歉。我对 Stack Overflow 还很陌生。

标签: pythondjangopostgresql

解决方案


推荐阅读