0

我似乎无法在概念上区分 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 页部分,所以如果可以的话,请不要向我推荐它们。我已经在向他们学习了。

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

4

1 回答 1

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
于 2013-02-05T20:00:24.060 回答