2013-02-05 102 views
0

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

多对多关系的两端都可以自动获取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=’[email protected]’) 
>>> 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> 

所以,我能得到从文章类通过外键的记者班。

许多到大量的实例:

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得到出版类的文章类就像我上面多到一类。那么M2M与M2one有什么不同呢?我可以用m2m做什么其他事情。 (我当然可以在两者上都做相反的处理,但我试图暂时忽略两者的反向关系,以免进一步混淆我自己。) 因此,为了更好地说出我的问题,通常情况下,人们通常会用m2m做哪些事情?不与m2one?

免责声明 - 新增了编程功能,但阅读了关于django官方文档模型的整个100页的部分,所以如果可以的话,请不要转介给我。我已经从他们那里学习了。

此外,我可以更好地了解代码,所以请包括一些代码示例,如果可以的话。

回答

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 
+0

我了解基础知识。我明白了。但是我可以用django ManyToManyField做些什么,我不能使用ManyToOne外键。 – masterpiece

+0

@masterpiece我做了一些编辑,希望他们帮助你 – juliomalegria

+0

@ julio.algeria欣赏它。所以“article.reporter.add(r)#这会引发一个错误!”。使用M2M字段可以在相关类的表格中进行更改/写入。但M2one上的外键只能“读取”。对不起,如果我今天过于密集。 – masterpiece