Django测验应用模型,用于多项选择题 [英] django quiz app model for multiple choice questions

查看:99
本文介绍了Django测验应用模型,用于多项选择题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在django中创建测验应用,我的django问题模型是这样的,

I am creating quiz app in django, my django model for questions is like this,

class Question(models.Model):
    questions = models.CharField(max_length=50, unique=True)
    choice1 = models.CharField(max_length=50, unique=True)
    choice2 = models.CharField(max_length=50, unique=True)
    choice3 = models.CharField(max_length=50, unique=True)
    choice4 = models.CharField(max_length=50, unique=True)
    correct_answer = models.CharField(max_length=50, unique=True)

这样很好还是将四个选项保存在postgres数组中或将选择保存在单独的表中。

is this fine or save the four options in postgres array or save the choices in separate table.

推荐答案

对于正确规范化的关系数据库架构,您需要一个独特的问题上带有外键的选择模型:

For a properly normalized relational database schema, you want a distinct Choice model with a foreign key on Question:

class Question(models.Model):
    question = models.CharField(...)

class Choice(models.Model):
    question = models.ForeignKey("Question", related_name="choices")
    choice = modelsCharField("Choice", max_length=50)
    position = models.IntegerField("position")

    class Meta:
        unique_together = [
            # no duplicated choice per question
            ("question", "choice"), 
            # no duplicated position per question 
            ("question", "position") 
        ]
        ordering = ("position",)

然后可以通过 myquestion.choices.all()问题的选择c>(并通过 mychoice.question Choice 中获取问题)。

And then you can get at a Question's choices with myquestion.choices.all() (and get the question from a Choice with mychoice.question).

请注意,这不会对一个问题的选择数量施加任何限制,甚至不要求一个问题至少具有一个相关的选择。

Note that this won't impose any limitation on the number of choices for a Question, not even mandates that a Question has at least one related Choice.

除非您有非常令人信服的理由进行其他操作,否则当您使用usi时,您想要的是正确标准化的架构ng关系数据库(rdbms不仅仅是简单的位桶,它们还提供了许多有用的功能-只要您具有正确的架构即可)。

Unless you have a very compelling reason to do otherwise, a properly normalized schema is what you want when using a relational database (rdbms are much more than mere bitbuckets, they offer a lot of useful features - as long as you do have a proper schema, that is).

这篇关于Django测验应用模型,用于多项选择题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆