Django REST Framework:POST请求:仅在数据不存在时如何保存数据

我是Django的新手,但我遇到了以下问题:

我有以下代码:

models.py:

class Vote(models.Model):
    answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
    user = models.ForeignKey(User,on_delete=models.CASCADE, related_name='votes', null=True)
    poll = models.ForeignKey(Poll, on_delete=models.CASCADE, null=True)

views.py:

class VoteViewSet(viewsets.ModelViewSet):
    permission_classes = [
        permissions.IsAuthenticated,
    ]
    serializer_class = VoteSerializer

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

serializer.py:

class VoteSerializer(serializers.ModelSerializer):
    class Meta:
        model = Vote
        fields = ('id', 'answer', 'user')

    def create(self, validated_data):
        answer = validated_data.get("answer", None)
        poll = answer.poll
        return Vote.objects.create(answer=answer, poll=poll, user=user)

每次我执行POST投票请求时,都会创建一个新的投票。

但是我想检查用户是否已经对投票进行了投票。

我有以下代码,但不知道放在哪里:

if not poll in [vote.poll for vote in user.votes.all()]:
    # Create Vote

如何正确检查用户是否已在民意调查中投票,如果没有,则创建投票?

评论
  • 请,带走
    请,带走 回复

    One of the easy solutions is, settings a unique_together constraint in the Meta section. If you do so, Django and DRF will take care of that.

    class Vote(models.Model):
        answer = models.ForeignKey(Answer, on_delete=models.CASCADE)
        user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='votes', null=True)
    
        class Meta:
            unique_together = ('answer', 'user')