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

时间:2015-12-16 15:23:28

标签: javascript python json django

我正在开发一个基于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

1 个答案:

答案 0 :(得分:0)

您可以对目标测验中的问题进行迭代,并创建一个以后可以传递给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]
        ]
    }
]