首页 > 解决方案 > 用于测验的 Django 视图

问题描述

我是 Django 的新手,我想制作测验应用程序,但我遇到了问题。我创建了 3 个模型(测验、问题、选择)。我想编写一个函数来返回具有相同测验标题的问题。

我试过这个

视图.py

def detail(request):
    sets = Quiz.objects.all()
    question = Question.objects.filter(sets.title)
    return render(request,'App/appdetail.html',{'question':question})

模型.py

class Quiz(models.Model):
    title = models.CharField(max_length=20)
    description = models.CharField(max_length=100)

    def __str__(self):
        return self.title

class Question(models.Model):
    set = models.ForeignKey(Quiz,on_delete=models.CASCADE)
    question_txt = models.CharField(max_length=100)

    def __str__(self):
        return self.question_txt

class Choice(models.Model):
    question = models.ForeignKey(Question,on_delete=models.CASCADE)
    choice_txt = models.CharField(max_length=20)
    boolean = models.BooleanField(default=False)

    def __str__(self):
        return self.choice_txt

错误信息

错误

标签: djangodjango-modelsdjango-views

解决方案


set您可以通过过滤模型中的测验外键问题来获得具有相同测验标题的所有问题Question

question = Question.objects.filter(set__title='your_quiz_title')

推荐阅读