gpt4 book ai didi

javascript - Django:从模型创建 JSON 对象以返回模板

转载 作者:行者123 更新时间:2023-11-28 06:35:35 25 4
gpt4 key购买 nike

我正在开发一个基于 Django 的测验,该测验将在 Javascript 的帮助下呈现。每个测验由多个问题组成,这些问题基本上有一个问题文本和多个选项(依次可以是正确的或不正确的 - 理论上可以有多个正确答案)。

我想从模板调用 get_all_questions_json 来接收如下内容:

{
{
"Question 1":
[
["Answer 1-1", true],
["Answer 1-2", false],
["Answer 1-3", false]
]
},

{
"Question 2":
[
["Answer 1-1", false],
["Answer 1-2", true],
["Answer 1-3", false]
]
},

{
"Question 3":
[
["Answer 1-1", false],
["Answer 1-2", false],
["Answer 1-3", true]
]
}
}

我怎样才能实现这一目标?

models.py:

class Quiz(models.Model):
name = models.CharField(max_length=80)
slug = models.SlugField()
# to do feedback texts

class Meta:
verbose_name_plural = "Quizzes"

def save(self, *args, **kwargs):
if not self.id:
# Newly created object, set slug
self.slug = slugify(self.name)
super(Quiz, self).save(*args, **kwargs)

def __str__(self):
return self.name

def get_all_questions(self):
return self.question_set.all()

def get_all_questions_json(self):
#

class Question(models.Model):
quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE)
text = models.CharField(max_length=200)
image = models.ImageField()

def __str__(self):
return self.text


class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
text = models.CharField(max_length=80)
iscorrect = models.BooleanField()

def __str__(self):
return self.text

最佳答案

您可以迭代目标测验中的问题并创建一个列表,稍后可以将其传递给 json.dumps

def get_all_questions_json(self):
import json
quiz_data = []
for question in self.question_set.all():
answers = []
quiz_data.append({
'text': question.text,
'answers': [
[answer.text, answer.is_correct]
for answer in question.answer_set.all()
],
})
return json.dumps(quiz_data)

输出将与您所说的略有不同,例如:

[
{
text: "Question 1",
answers: [
["Answer 1-1", true],
["Answer 1-2", false],
["Answer 1-3", false]
]
},
{
text: "Question 2",
answers: [
["Answer 1-1", false],
["Answer 1-2", true],
["Answer 1-3", false]
]
},
{
text: "Question 3",
answers: [
["Answer 1-1", false],
["Answer 1-2", false],
["Answer 1-3", true]
]
}
]

关于javascript - Django:从模型创建 JSON 对象以返回模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34315794/

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