在django教程中,它对民意调查结构进行了建模:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
但我总是想知道为什么它们不像ManyToMany关系那样实现:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
choices = models.ManyToManyField(Choice)
class Choice(models.Model):
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
优缺点都有什么?
我敢肯定,他们用一个ForeignKey(一对多)在本教程中关系,因为他们试图保持例子尽可能简单,只有两个型号:Question
和Choice
。注意,这votes
是Choice
模型的一个字段,这使得显示投票结果非常简单。
如果在进行民意测验时,每个问题都有相同的选择(完全同意,有点同意等),那么ManyToMany关系可能是合适的。但这使事情变得更加复杂。您为ManyToMany关系建议的模型是:
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
choices = models.ManyToManyField(Choice)
class Choice(models.Model):
choice_text = models.CharField(max_length=200)
votes = models.IntegerField(default=0)
但是,如果不进行一些更改,它将无法正常工作。votes
仍然是Choice
表格的一个字段,但是现在每个选择都适用于许多问题。您将能够看到“强烈同意”选择获得38票,但您无法确定选民同意哪些问题。为了能够正确地将选票制成表格,您必须执行以下操作
from django.db import models
class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
choices = models.ManyToManyField('Choice', through='QuestionChoices')
class Choice(models.Model):
choice_text = models.CharField(max_length=200)
class QuestionChoices(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE)
choice = models.ForeignKey(Choice, on_delete=models.CASCADE)
votes = models.IntegerField(default=0)
现在,您可以准确地列出每个问题选择组合有多少人投票,但是它比较复杂并且不太适合入门教程。
使用您提出的ManyToMany模型,Django会QuestionChoices
在幕后自动创建模型,但是为了将votes
字段附加到该模型,您必须自己明确地进行建模。
如果您有可以建模为OneToMany或ManyToMany的关系,则优缺点取决于您的特定应用程序。通常,您想使用最能真实反映现实情况的模型。但是,您还必须考虑如何更新和汇总数据,并尝试做出最佳折衷。根据我的经验,在很多情况下选择困难。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句