Sak*_*vam 2 python django postgresql
我正在django中创建测验应用,我的django模型中的问题是这样的,
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)
Run Code Online (Sandbox Code Playgroud)
很好还是将这四个选项保存在postgres数组中,或者将选择保存在单独的表中。
对于正确规范化的关系数据库架构,您需要一个Choice带有外键的独特模型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",)
Run Code Online (Sandbox Code Playgroud)
然后你就可以在得到Question的选择与myquestion.choices.all()(和从获取的问题Choice与mychoice.question)。
注意,这不会对一个问题的选择数量施加任何限制,甚至不要求一个问题至少具有一个相关的选择。
除非您有非常令人信服的理由,否则使用关系数据库时需要的是正确归一化的架构(rdbms远不只是位桶,它们提供了许多有用的功能-只要您确实拥有正确的架构, 那是)。
| 归档时间: |
|
| 查看次数: |
3743 次 |
| 最近记录: |