Django数据库关系 - 多对多,多对一

时间:2013-02-05 19:51:25

标签: python django

我似乎无法在概念上区分django中的多对一和多对多关系。我理解他们如何在SQL和数据库中工作,并通过心脏理解外键的概念等,例如我不理解以下内容:

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

MANY-TO-ONE示例:

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’,)

我的问题是 - 我可以通过ManyToManyField在Article类上获得Publication类,就像我在Many-to-One类中所做的那样。那么M2M与M2one有何不同?我可以用m2m做的其他事情是什么。 (我当然可以对两者做反转,但我暂时试图忽略两者的反向关系,以免进一步混淆我自己。) 所以为了更好地说出我的问题,通常用m2m做什么呢?哪一个通常不用m2one?

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

此外,我可以更好地理解代码,所以请尽可能包含一些代码示例。

1 个答案:

答案 0 :(得分: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