# Django 5.2.8 documentation

# 多对一关联

要定义多对一关系，请使用 `ForeignKey`。

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

    from django.db import models

    class Reporter(models.Model):
        first_name = models.CharField(max_length=30)
        last_name = models.CharField(max_length=30)
        email = models.EmailField()

        def __str__(self):
            return f"{self.first_name} {self.last_name}"

    class Article(models.Model):
        headline = models.CharField(max_length=100)
        pub_date = models.DateField()
        reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)

        def __str__(self):
            return self.headline

        class Meta:
            ordering = ["headline"]

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

创建几个 `Reporters`：

    >>> r = Reporter(first_name="John", last_name="Smith", email="john@example.com")
    >>> r.save()

    >>> r2 = Reporter(first_name="Paul", last_name="Jones", email="paul@example.com")
    >>> r2.save()

创建一篇 `Article`：

    >>> from datetime import date
    >>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
    >>> a.save()

    >>> a.reporter.id
    1

    >>> a.reporter
    <Reporter: John Smith>

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

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

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

    >>> r = a.reporter

通过 `Reporter` 对象创建一篇 `Article`：

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

创建一篇新的文章：

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

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

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

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

    >>> r.article_set.add(r2)
    Traceback (most recent call last):
    ...
    TypeError: 'Article' instance expected, got <Reporter: Paul Jones>

    >>> r.article_set.all()
    <QuerySet [<Article: John's second story>, <Article: This is a test>]>
    >>> r2.article_set.all()
    <QuerySet [<Article: Paul's story>]>

    >>> r.article_set.count()
    2

    >>> r2.article_set.count()
    1

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

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

    >>> r.article_set.filter(headline__startswith="This")
    <QuerySet [<Article: This is a test>]>

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

这里隐含了精确匹配：

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

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

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

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

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

    >>> Article.objects.filter(reporter__in=[1, 2]).distinct()
    <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
    >>> Article.objects.filter(reporter__in=[r, r2]).distinct()
    <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>

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

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

在相反的方向进行查询：

    >>> Reporter.objects.filter(article__pk=1)
    <QuerySet [<Reporter: John Smith>]>
    >>> Reporter.objects.filter(article=1)
    <QuerySet [<Reporter: John Smith>]>
    >>> Reporter.objects.filter(article=a)
    <QuerySet [<Reporter: John Smith>]>

    >>> Reporter.objects.filter(article__headline__startswith="This")
    <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
    >>> Reporter.objects.filter(article__headline__startswith="This").distinct()
    <QuerySet [<Reporter: John Smith>]>

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

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

查询可以循环：

    >>> Reporter.objects.filter(article__reporter__first_name__startswith="John")
    <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
    >>> Reporter.objects.filter(article__reporter__first_name__startswith="John").distinct()
    <QuerySet [<Reporter: John Smith>]>
    >>> Reporter.objects.filter(article__reporter=r).distinct()
    <QuerySet [<Reporter: John Smith>]>

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

    >>> Article.objects.all()
    <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
    >>> Reporter.objects.order_by("first_name")
    <QuerySet [<Reporter: John Smith>, <Reporter: Paul Jones>]>
    >>> r2.delete()
    >>> Article.objects.all()
    <QuerySet [<Article: John's second story>, <Article: This is a test>]>
    >>> Reporter.objects.order_by("first_name")
    <QuerySet [<Reporter: John Smith>]>

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

    >>> Reporter.objects.filter(article__headline__startswith="This").delete()
    >>> Reporter.objects.all()
    <QuerySet []>
    >>> Article.objects.all()
    <QuerySet []>