python - 将发布请求保存到数据库后是否可以返回 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 还很陌生。
解决方案
推荐阅读
- python - 缓存结果似乎比重新计算结果慢
- r - 如何根据某些变量绘制条形图的条件彩色轮廓?
- java - 将 MySQL 数据库打包到 java se 应用程序
- r - 如何在 R 中使用 mapview() 标题给出地图?
- clang - 如何在 llvm ir 中创建 thread_local 变量?
- python - python函数应该总是返回一些值有什么原因吗?
- javascript - 如何从返回承诺的回调函数中获取数据?
- python - 将 GeoJSON 加载到 GeoPandas 数据帧中 - 格式错误或给出“引发 TypeError”
- python - 在等待数据库查询响应时从外部停止线程
- ruby-on-rails - 如何创建带有测试消息的新 ActiveModel::Error?