Python Django数据库关系-多对多、多对一

Python Django数据库关系-多对多、多对一,python,django,Python,Django,我似乎无法从概念上区分django中的多对一和多对多关系。我了解它们在SQL和数据库中的工作方式,并熟记外键等概念,但例如,我不了解以下内容: 多对多关系的两端都可以自动访问另一端的API。API就像一个“向后”的一对多关系一样工作。然而,我仍然无法从概念上看到它 多对一示例: class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharFiel

我似乎无法从概念上区分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>
我的问题是——我可以通过文章类的ManyToManyField进入出版物类,就像我在多对一类中所做的那样。那么M2M和M2one有何不同呢?我还可以用m2m做些什么。(当然,我可以在这两个方面都做反向操作,但我正在尝试暂时忽略这两个方面的反向关系,以免进一步混淆自己。) 因此,为了更好地表达我的问题,一个人通常用m2m做什么,而另一个人通常用m2one做什么

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

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

一名记者可能有多篇文章,但一篇文章只有一篇 记者

另一方面,

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


我了解基本情况。我明白了。但对于django ManyToManyField,我还能做什么呢?我不能用ManyToOne外键。@julio.algeria,谢谢。所以“article.reporter.add(r)#这将引起一个错误!”。使用M2M字段可以在相关类的表中进行更改/写入。但M21上的外键只能“读取”。对不起,如果我今天太浓了。
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’,)
# 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