【问题标题】:Django database relationships - many-to-many, many-to-oneDjango 数据库关系——多对多、多对一
【发布时间】:2013-02-05 19:51:24
【问题描述】:

我似乎无法在概念上区分 django 中的多对一和多对多关系。我了解它们在 SQL 和数据库中的工作方式,并牢记外键等概念,但例如我不了解以下内容:

多对多关系的两端都可以自动访问另一端的 API。 API 就像“向后”的一对多关系一样工作。但是,我仍然无法从概念上看到它。

多对一示例:

class Reporter(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)
    email = models.EmailField()

    def __unicode__(self):
        return u"%s %s" % (self.first_name, self.last_name)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    pub_date = models.DateField()
    reporter = models.ForeignKey(Reporter)

    def __unicode__(self):
        return self.headline

    class Meta:
        ordering = (’headline’,)

我可以这样做:

>>> r = Reporter(first_name=’John’, last_name=’Smith’, email=’john@example.com’)
>>> r.save()
>>> a = Article(id=None, headline="This is a test", pub_date=datetime(2005, 7, 27), reporter=r)
>>> a.save()
>>> a.reporter
<Reporter: John Smith>

所以,我可以通过外键从 Articles 类进入 Reporters 类。

多对多示例:

class Publication(models.Model):
    title = models.CharField(max_length=30)

    def __unicode__(self):
        return self.title

    class Meta:
        ordering = (’title’,)

class Article(models.Model):
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

    def __unicode__(self):
        return self.headline

    class Meta:
        ordering = (’headline’,)

我的问题是 - 我可以通过 Article 类上的 ManyToManyField 进入 Publication 类,就像我在上面的多对一类中所做的一样。那么 M2M 与 M2one 有何不同?我可以用 m2m 做的其他事情是什么。 (我当然可以在两者上做反向,但我暂时试图忽略两者的反向关系,以免进一步混淆自己。) 因此,为了更好地表达我的问题,一个人通常对 m2m 做什么,而一个人通常不会对 m2one 做什么?

免责声明 - 编程新手,但阅读了 django 官方文档模型的整个 100 页部分,所以如果可以的话,请不要向我推荐它们。我已经在向他们学习了。

另外,我可以更好地理解代码,所以如果可以的话,请提供一些代码示例。

【问题讨论】:

    标签: python django


    【解决方案1】:

    一个记者可以有许多篇文章,但一篇文章只有一篇 记者。

    # This will get the reporter of an article
    article.reporter
    # This will get all the articles of a reporter
    reporter.article_set.all()
    # You cannot add another reporter to an article
    article.reporter.add(r) # This will raise an Error!
    

    另一方面,

    一篇文章可能有许多出版物,而出版物可能与许多文章相关。

    # This will get all the publications of an article
    article.publications.all()
    # This will get all the related articles of a publication
    publication.article_set.all()
    # You CAN add another publication to an article
    article.publications.add(p) # No Error here
    

    【讨论】:

    • 我了解基础知识。我明白了。但是我可以用 django ManyToManyField 做些什么,而我不能用 ManyToOne 外键。
    • @julio.algeria 感谢它。所以“article.reporter.add(r) # 这会引发一个错误!”。使用 M2M 字段可以在相关类的表中进行更改/写入。但 M2one 上的外键只能“读取”。对不起,如果我今天过于密集。
    猜你喜欢
    • 2015-07-05
    • 2017-03-18
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多