何时在ForeignKey上使用ManyToMany字段? [英] When to use a ManyToMany field over a ForeignKey?

查看:134
本文介绍了何时在ForeignKey上使用ManyToMany字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑到我们有两个Django模型,问答。
一个问题可以有很多答案,但答案只能有一个与之相关的问题。
我们可以将关系建模为:

 类问题(models.Model):
text = models .CharField(...)
answers = models.ManyToManyField('Answer')

类答案(models.Model):
text = models.CharField(... )

我们也可以将其建模为:

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

class答案(models.Model):
text = models.CharField(...)
question = models.ForeignKey('Question')

Django经理允许我们向后追踪ForeignKey和ManyToManyField。
我们应该使用什么模型结构?

解决方案

一对多当然。您可以使用多对多关系来实现同样的事情,但是您会使事情变得复杂,您将为表演打击付出代价。



从数据库建模的角度来考虑它(忘记ORM)。你为什么要这样做:问题 - >多对多经理 - >答案而不是:问题 - >答案


Consider that we have two Django models, Question and Answer. A question can have many answers to it, but an answer can have only one question related to it. We can model the relationship as:

class Question(models.Model):
    text     = models.CharField(...)
    answers  = models.ManyToManyField('Answer')

class Answer(models.Model):
    text     = models.CharField(...)

We can also model it as:

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

class Answer(models.Model):
    text     = models.CharField(...)
    question = models.ForeignKey('Question')

Django managers allow us to follow both ForeignKey and ManyToManyField backwards. What model structure should we use?

解决方案

one-to-many of course. You could achieve the same thing using many-to-many relationship but you'll complicate things a lot and you'll pay for a performance hit.

Think of it from a database modelling point of view (forget the ORM). Why would you want to do: question -> many-to-many-manager -> answers instead of having: question -> answers.

这篇关于何时在ForeignKey上使用ManyToMany字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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