创建序列化器以显示正确的数据

时间:2018-11-20 23:49:02

标签: python django django-rest-framework django-queryset

我有4个模型。 UserQuestionChoiceVoting。这基本上是我要创建的民意测验应用程序。一个问题可以有很多选择。 Voting模型跟踪每个用户选择的答案。

我想做的是检索所有问题,并检查登录用户为每个问题选择的选择。这是模型:

class Question(models.Model):
    user            = models.ForeignKey(User, on_delete=models.CASCADE)
    status          = models.CharField(max_length=200)
    total_votes     = models.IntegerField(default=0)

class Choice(models.Model):
    question    = models.ForeignKey(Question, on_delete=models.CASCADE)
    choice      = models.CharField(max_length=120)
    vote_count  = models.IntegerField(default=0)

class Voting(models.Model):
    user    = models.ForeignKey(User, on_delete=models.CASCADE)
    choice  = models.ForeignKey(Choice, on_delete=models.CASCADE)

这是我想要显示数据的方式:

{
    user: 2
    status: "Hello"
    total_votes: 101
    choices: [
                {
                    "id": 2,
                    "choice": "first choice",
                    "vote_count": 31,
                    "question": 3
                },
                {
                    "id": 4,
                    "choice": "second choice",
                    "vote_count": 70,
                    "question": 3
                }
            ],
    choice_selected: 2
}

在上面的数据中,已登录的用户在此特定问题中选择了选项2。

编辑:我尝试添加序列化程序,但显示“投票”类型的对象无法JSON序列化

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = '__all__'

class QuestionSerializer(serializers.ModelSerializer):
    choices = ChoiceSerializer(source='choice_set', many=True)
    class Meta:
        model = Question
        fields = '__all__'


class GetProfileQuestions(ListAPIView):
    serializer_class = QuestionSerializer

    def get_queryset(self):
        return Question.objects.all()

此查询成功打印出每个问题及其选择。但是,如何使它也能打印出用户为每个问题选择的选项?

class VotingSerializer(serializers.ModelSerializer):

    class Meta:
        model = Voting
        fields = '__all__'    


class ChoiceSerializer(serializers.ModelSerializer):
    votes = VotingSerializer(source='voting_set', many=True)
    class Meta:
        model = Choice
        fields = '__all__'


class QuestionSerializer(serializers.ModelSerializer):
    choices = ChoiceSerializer(source='choice_set', many=True)
    choice_selected = serializers.SerializerMethodField()
    class Meta:
        model = Question
        fields = '__all__'

    def get_choice_selected(self, obj):
        choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
        return choice_selected

1 个答案:

答案 0 :(得分:0)

我想您会在QuestionSerializer类中使用它

 choice_selected = serializers.SerializerMethodField()

并在QuestionSerializer中定义一个类似于以下内容的方法……

def get_choice_selected(self, obj):
        choice_selected = Voting.objects.filter(choice__question=obj.id).filter(user=obj.user)
        return choice_selected

以上未经测试。