0

拥有这两个课程我总是怀疑哪个是“链接”它们的最佳实践(如果有的话)

问题

class Question(models.Model):
    text = models.CharField('Question',max_length=120)
    created = models.DateTimeField(auto_now_add=True)
    opens = models.DateTimeField()
    closes = models.DateTimeField()

回答

class Answer(models.Model):
    text =  models.CharField('Answer',max_length=120)
    votes = models.IntegerField(default=0)

错误 -我可以将此行添加到 Answer (这是复制/粘贴错误):

answers = models.ForeignKey(Answer)

编辑:

answers = models.ManyToManyField(Answer)

我可以将此行添加到答案:

question = models.ForeignKey(Question)

我想知道这是否真的无关紧要,或者我应该考虑不同的方面。

谢谢!

4

2 回答 2

2
class Question: 
    answer = models.ForeignKey(Answer)

"This particular question has only one possible answer".


class Answer: 
    question = models.ForeignKey(Question)

"This answer belongs to one particular question only, but that question might have multiple separate answers"


class Answer:
    question = models.ManyToManyField(Question)

"This particular answer is an answer to multiple questions. So questions can have multiple separate answers"


class Question:
    answers = modes.ManyToManyField(Answer)

"This question has multiple distinct answers. Also answers can belong to multiple questions." [Best approach]


An question has to have answers. You don't make an answer (usually) to answer multiple questions, instead, an answer answers one particular question, but there may be multiple answers (from different users for example). Therefore I'd pick 4 .

于 2012-04-05T10:20:12.073 回答
1
answers = models.ForeignKey(Answer)

question = models.ForeignKey(Question)

这些是不等价的。第一个(假设您的意思是第一个应该打开Question将意味着一个问题只有一个答案,但一个答案有多个问题 - 猜测这不是您想要的。

The second will mean that an answer has a single question and that questions will have more than one answer which is presumably what you want. By default this will add an answer_set field to Question containing all of a questions answers.

于 2012-04-05T10:19:45.537 回答