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

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

本文介绍了创建序列化器以显示正确的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有4个模型。 用户,问题,选择和投票。这基本上是我要创建的民意调查应用。一个问题可以有很多选择。 投票模型跟踪每个用户选择的答案。

I have 4 models. User, Question, Choice, and Voting. This is basically a polls app I'm trying to create. A question can have many choices. The Voting model tracks what each user chose as their answer.

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

What I'd like to do is retrieve all the questions and also check what choice the logged in user selected for each question. Here's the models:

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)

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

Here's how I want the data displayed:

{
    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。

In the data above, the logged in user selected choice 2 in this specific question.

编辑:我尝试添加序列化程序,但显示的对象类型为'投票'不能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()

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

This query successfully prints out each question and its choices. However, how do I make it so that it also prints out which choice the user selected for each question?

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


推荐答案

我认为您会在自己的QuestionSerializer类中使用它

I think you will want this in your QuestionSerializer class

 choice_selected = serializers.SerializerMethodField()

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

and define a method that looks something like this in QuestionSerializer …

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

以上未经测试。

这篇关于创建序列化器以显示正确的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 12:13