多对一关联

要定义多对一关系,请使用 ForeignKey

在这个例子中,一个 Reporter 可以与多个 Article 对象关联,但一个 Article 只能有一个 Reporter 对象:

  1. from django.db import models
  2. class Reporter(models.Model):
  3. first_name = models.CharField(max_length=30)
  4. last_name = models.CharField(max_length=30)
  5. email = models.EmailField()
  6. def __str__(self):
  7. return f"{self.first_name} {self.last_name}"
  8. class Article(models.Model):
  9. headline = models.CharField(max_length=100)
  10. pub_date = models.DateField()
  11. reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
  12. def __str__(self):
  13. return self.headline
  14. class Meta:
  15. ordering = ["headline"]

下面是可以使用PythonAPI工具执行的操作示例。

创建几个 Reporters

  1. >>> r = Reporter(first_name="John", last_name="Smith", email="john@example.com")
  2. >>> r.save()
  3. >>> r2 = Reporter(first_name="Paul", last_name="Jones", email="paul@example.com")
  4. >>> r2.save()

创建一篇 Article

  1. >>> from datetime import date
  2. >>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
  3. >>> a.save()
  4. >>> a.reporter.id
  5. 1
  6. >>> a.reporter
  7. <Reporter: John Smith>

请注意,在将对象分配给外键关系之前,您必须保存该对象。例如,创建一个未保存的 ReporterArticle 会引发 ValueError

  1. >>> r3 = Reporter(first_name="John", last_name="Smith", email="john@example.com")
  2. >>> Article.objects.create(
  3. ... headline="This is a test", pub_date=date(2005, 7, 27), reporter=r3
  4. ... )
  5. Traceback (most recent call last):
  6. ...
  7. ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.

Article 对象可以访问与其相关联的 Reporter 对象:

  1. >>> r = a.reporter

通过 Reporter 对象创建一篇 Article

  1. >>> new_article = r.article_set.create(
  2. ... headline="John's second story", pub_date=date(2005, 7, 29)
  3. ... )
  4. >>> new_article
  5. <Article: John's second story>
  6. >>> new_article.reporter
  7. <Reporter: John Smith>
  8. >>> new_article.reporter.id
  9. 1

创建一篇新的文章:

  1. >>> new_article2 = Article.objects.create(
  2. ... headline="Paul's story", pub_date=date(2006, 1, 17), reporter=r
  3. ... )
  4. >>> new_article2.reporter
  5. <Reporter: John Smith>
  6. >>> new_article2.reporter.id
  7. 1
  8. >>> r.article_set.all()
  9. <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>

将相同的文章添加到不同的文章集合中 - 检查它是否移动:

  1. >>> r2.article_set.add(new_article2)
  2. >>> new_article2.reporter.id
  3. 2
  4. >>> new_article2.reporter
  5. <Reporter: Paul Jones>

添加错误类型的对象会引发 TypeError:

  1. >>> r.article_set.add(r2)
  2. Traceback (most recent call last):
  3. ...
  4. TypeError: 'Article' instance expected, got <Reporter: Paul Jones>
  5. >>> r.article_set.all()
  6. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  7. >>> r2.article_set.all()
  8. <QuerySet [<Article: Paul's story>]>
  9. >>> r.article_set.count()
  10. 2
  11. >>> r2.article_set.count()
  12. 1

注意在最后的例子里,那篇 article 的 reporter 已经从 John 变为 Paul。

相关管理器也支持字段查找。API 会自动按需遍历关系。使用双下划线来分隔关系。这可以深入到您需要的任何级别,没有限制。例如:

  1. >>> r.article_set.filter(headline__startswith="This")
  2. <QuerySet [<Article: This is a test>]>
  3. # Find all Articles for any Reporter whose first name is "John".
  4. >>> Article.objects.filter(reporter__first_name="John")
  5. <QuerySet [<Article: John's second story>, <Article: This is a test>]>

这里隐含了精确匹配:

  1. >>> Article.objects.filter(reporter__first_name="John")
  2. <QuerySet [<Article: John's second story>, <Article: This is a test>]>

在相关字段上进行两次查询。这将在 WHERE 子句中转换为 AND 条件:

  1. >>> Article.objects.filter(reporter__first_name="John", reporter__last_name="Smith")
  2. <QuerySet [<Article: John's second story>, <Article: This is a test>]>

对于相关查找,您可以提供主键值或显式传递相关对象:

  1. >>> Article.objects.filter(reporter__pk=1)
  2. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  3. >>> Article.objects.filter(reporter=1)
  4. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  5. >>> Article.objects.filter(reporter=r)
  6. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  7. >>> Article.objects.filter(reporter__in=[1, 2]).distinct()
  8. <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
  9. >>> Article.objects.filter(reporter__in=[r, r2]).distinct()
  10. <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>

您还可以使用查询集而不是实例的文字列表:

  1. >>> Article.objects.filter(
  2. ... reporter__in=Reporter.objects.filter(first_name="John")
  3. ... ).distinct()
  4. <QuerySet [<Article: John's second story>, <Article: This is a test>]>

在相反的方向进行查询:

  1. >>> Reporter.objects.filter(article__pk=1)
  2. <QuerySet [<Reporter: John Smith>]>
  3. >>> Reporter.objects.filter(article=1)
  4. <QuerySet [<Reporter: John Smith>]>
  5. >>> Reporter.objects.filter(article=a)
  6. <QuerySet [<Reporter: John Smith>]>
  7. >>> Reporter.objects.filter(article__headline__startswith="This")
  8. <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
  9. >>> Reporter.objects.filter(article__headline__startswith="This").distinct()
  10. <QuerySet [<Reporter: John Smith>]>

在相反的方向进行计数与 distinct() 结合使用:

  1. >>> Reporter.objects.filter(article__headline__startswith="This").count()
  2. 3
  3. >>> Reporter.objects.filter(article__headline__startswith="This").distinct().count()
  4. 1

查询可以循环:

  1. >>> Reporter.objects.filter(article__reporter__first_name__startswith="John")
  2. <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
  3. >>> Reporter.objects.filter(article__reporter__first_name__startswith="John").distinct()
  4. <QuerySet [<Reporter: John Smith>]>
  5. >>> Reporter.objects.filter(article__reporter=r).distinct()
  6. <QuerySet [<Reporter: John Smith>]>

如果删除了一个记者,他们的文章将被删除(假设使用 django.db.models.ForeignKey.on_delete 设置为 CASCADE 来定义外键,这是默认值):

  1. >>> Article.objects.all()
  2. <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
  3. >>> Reporter.objects.order_by("first_name")
  4. <QuerySet [<Reporter: John Smith>, <Reporter: Paul Jones>]>
  5. >>> r2.delete()
  6. >>> Article.objects.all()
  7. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  8. >>> Reporter.objects.order_by("first_name")
  9. <QuerySet [<Reporter: John Smith>]>

您可以在查询中使用 JOIN 进行删除操作:

  1. >>> Reporter.objects.filter(article__headline__startswith="This").delete()
  2. >>> Reporter.objects.all()
  3. <QuerySet []>
  4. >>> Article.objects.all()
  5. <QuerySet []>