gpt4 book ai didi

python - 如何为 Django REST Framework 正确定义模型/序列化器?

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:12 26 4
gpt4 key购买 nike

我们正在使用此堆栈创建一个移动网络应用程序:

python Django,SQLite 数据库Django 休息 ionic Cordova 角度JS

这是一个测验应用程序,您可以在其中回答 4 个多项选择的问题。问题和答案存储在数据库中。在 REST 框架的帮助下创建了一个端点。

有了这个 JSON 文件,我们的 Angular JS Controller 异步工作。问题是在 model.py 中定义答案。它涉及数组中的数组。

我们正在尝试使用 Django REST 获取此结构:

[
{
"question" : "Java was originally developed at _______________",
"answer" : [
{"id" : 0, "text" : "Sun Microsystems"},
{"id" : 1, "text" : "Intel"},
{"id" : 2, "text" : "Hewlett-Packard"},
{"id" : 3, "text" : "Oracle"}
],
"correct" : 0
},
]

这就是我们所拥有的:

[
{
"question": "Java was originally developed at _______________",
"answer": [
{
"url": "http://127.0.0.1:8000/api/answer/1/",
"answerid": 0,
"text": "Sun Microsystems"
},
{
"url": "http://127.0.0.1:8000/api/answer/2/",
"answerid": 1,
"text": "Intel"
},
{
"url": "http://127.0.0.1:8000/api/answer/3/",
"answerid": 2,
"text": "Hewlett-Packard"
},
{
"url": "http://127.0.0.1:8000/api/answer/4/",
"answerid": 3,
"text": "Oracle"
}
],
"correct": 0
}
]

这是我们的 models.py:

from django.db import models

class Answer(models.Model):
answerid = models.IntegerField()
text = models.TextField()

class Question(models.Model):
question = models.CharField(max_length=200)
answer = models.ManyToManyField(Answer)
correct = models.IntegerField()

序列化器:

from quiz.models import Question, Answer
from rest_framework import routers, serializers, viewsets

class AnswerSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Answer
fields = ('answerid', 'text')

class QuestionSerializer(serializers.HyperlinkedModelSerializer):

class Meta:
model = Question
fields = ('question', 'answer', 'correct')
read_only_fields = ('answer',)
depth = 1

# ViewSets define the view behavior.
class QuestionViewSet(viewsets.ModelViewSet):
queryset = Question.objects.all()
serializer_class = QuestionSerializer

class AnswerViewSet(viewsets.ModelViewSet):
queryset = Answer.objects.all()
serializer_class = AnswerSerializer

是否可以通过某种方式删除我们解决方案中的 url?

最佳答案

这些 url 是因为你继承了 HyperlinkedModelSerializer

class QuestionSerializer(serializers.HyperlinkedModelSerializer):
...

如果您不需要它们,请使用不同的基类 - 也许只是一个 ModelSerializer .

关于python - 如何为 Django REST Framework 正确定义模型/序列化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38643178/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com