python - Django 使用序列化器在 Restframework 中进行 API 调用的一对多关系

标签 python django api django-rest-framework

我有两个模型,分别是问题和与该问题一致的选择集。我想结合这两个模型来创建一个 API,它显示问题列表及其选择。

这些是我的模型:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField("date published")

    def __str__(self):
        return self.question_text


class Choice(models.Model):
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    question = models.ForeignKey(Question, on_delete=models.CASCADE)

    def __str__(self):
        return self.choice_text

这些是我的序列化器

class QuestionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Question
        fields = ('question_text',)


class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = ('choice_text','question',)


class QuestionWithAnswer(serializers.ModelSerializer):
    question = QuestionSerializer(many=True)

    class Meta:
        model = Choice
        fields = ('question',)

这是 View 类

@api_view(['GET', 'POST', ])
def getquestionWithChoices(request):
    question = Question.objects.all()
    serializer = QuestionWithAnswer
    return Response(serializer.data)

我尝试了很多方法,但无法得到以下输出。

  [
          {
            "id": 1,
            "question_text": "What's your name?",
            "pub_date": "2019-04-13T05:27:21Z",
            "choices": [
              {
                "id": 1,
                "choice_text": "fred",
                "votes": 0,
                "question": 1
              },
              {
                "id": 2,
                "choice_text": "bob",
                "votes": 0,
                "question": 1
              },
              {
                "id": 3,
                "choice_text": "rachel",
                "votes": 0,
                "question": 1
              }
            ]
          },
          {
            "id": 2,
            "question_text": "What's your age?",
            "pub_date": "2019-04-13T05:27:39Z",
            "choices": [
              {
                "id": 4,
                "choice_text": "15",
                "votes": 4,
                "question": 2
              },
              {
                "id": 5,
                "choice_text": "16",
                "votes": 2,
                "question": 2
              },
              {
                "id": 6,
                "choice_text": "17",
                "votes": 2,
                "question": 2
              }
            ]
          }
        ]

最佳答案

您没有正确实例化序列化器。

@api_view(['GET', 'POST', ])
def getquestionWithChoices(request):
    questions = Question.objects.all()
    serializer = QuestionWithAnswer(questions, many=True)
    return Response(serializer.data)

并且您的序列化器也未正确定义:

class ChoiceSerializer(serializers.ModelSerializer):
    class Meta:
        model = Choice
        fields = ('id', 'votes', 'choice_text','question',)


class QuestionWithAnswer(serializers.ModelSerializer):
    choices = ChoiceSerializer(many=True)

    class Meta:
        model = Question
        fields = ('id', 'question_text', 'pub_date', 'choices')

关于python - Django 使用序列化器在 Restframework 中进行 API 调用的一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55707049/

相关文章:

python - 我可以制作一个脚本来打开终端并运行 .py 吗?

python - 打开上传的 CSV 文件时出现类型错误

Flutter 中的 Azure API(面部识别)

java - 持久通知的前台服务

python - 在python中导入字典

python - 等价于 Python 中的 C++ union

jQuery + Django : transfer 350KB of textual data from server to client?

javascript - 本地存储多 key 存储

python - 是否有生产安全的方法来衡量在使用 Python 的生产中花费的时间?

python - 如何获取查询集中的当前事件?