many_to_one.txt 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. =========================
  2. Many-to-one relationships
  3. =========================
  4. To define a many-to-one relationship, use :class:`~django.db.models.ForeignKey`.
  5. In this example, a ``Reporter`` can be associated with many ``Article``
  6. objects, but an ``Article`` can only have one ``Reporter`` object::
  7. from django.db import models
  8. class Reporter(models.Model):
  9. first_name = models.CharField(max_length=30)
  10. last_name = models.CharField(max_length=30)
  11. email = models.EmailField()
  12. def __str__(self):
  13. return f"{self.first_name} {self.last_name}"
  14. class Article(models.Model):
  15. headline = models.CharField(max_length=100)
  16. pub_date = models.DateField()
  17. reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
  18. def __str__(self):
  19. return self.headline
  20. class Meta:
  21. ordering = ["headline"]
  22. What follows are examples of operations that can be performed using the Python
  23. API facilities.
  24. Create a few Reporters:
  25. .. code-block:: pycon
  26. >>> r = Reporter(first_name="John", last_name="Smith", email="john@example.com")
  27. >>> r.save()
  28. >>> r2 = Reporter(first_name="Paul", last_name="Jones", email="paul@example.com")
  29. >>> r2.save()
  30. Create an Article:
  31. .. code-block:: pycon
  32. >>> from datetime import date
  33. >>> a = Article(id=None, headline="This is a test", pub_date=date(2005, 7, 27), reporter=r)
  34. >>> a.save()
  35. >>> a.reporter.id
  36. 1
  37. >>> a.reporter
  38. <Reporter: John Smith>
  39. Note that you must save an object before it can be assigned to a foreign key
  40. relationship. For example, creating an ``Article`` with unsaved ``Reporter``
  41. raises ``ValueError``:
  42. .. code-block:: pycon
  43. >>> r3 = Reporter(first_name="John", last_name="Smith", email="john@example.com")
  44. >>> Article.objects.create(
  45. ... headline="This is a test", pub_date=date(2005, 7, 27), reporter=r3
  46. ... )
  47. Traceback (most recent call last):
  48. ...
  49. ValueError: save() prohibited to prevent data loss due to unsaved related object 'reporter'.
  50. Article objects have access to their related Reporter objects:
  51. .. code-block:: pycon
  52. >>> r = a.reporter
  53. Create an Article via the Reporter object:
  54. .. code-block:: pycon
  55. >>> new_article = r.article_set.create(
  56. ... headline="John's second story", pub_date=date(2005, 7, 29)
  57. ... )
  58. >>> new_article
  59. <Article: John's second story>
  60. >>> new_article.reporter
  61. <Reporter: John Smith>
  62. >>> new_article.reporter.id
  63. 1
  64. Create a new article:
  65. .. code-block:: pycon
  66. >>> new_article2 = Article.objects.create(
  67. ... headline="Paul's story", pub_date=date(2006, 1, 17), reporter=r
  68. ... )
  69. >>> new_article2.reporter
  70. <Reporter: John Smith>
  71. >>> new_article2.reporter.id
  72. 1
  73. >>> r.article_set.all()
  74. <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
  75. Add the same article to a different article set - check that it moves:
  76. .. code-block:: pycon
  77. >>> r2.article_set.add(new_article2)
  78. >>> new_article2.reporter.id
  79. 2
  80. >>> new_article2.reporter
  81. <Reporter: Paul Jones>
  82. Adding an object of the wrong type raises TypeError:
  83. .. code-block:: pycon
  84. >>> r.article_set.add(r2)
  85. Traceback (most recent call last):
  86. ...
  87. TypeError: 'Article' instance expected, got <Reporter: Paul Jones>
  88. >>> r.article_set.all()
  89. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  90. >>> r2.article_set.all()
  91. <QuerySet [<Article: Paul's story>]>
  92. >>> r.article_set.count()
  93. 2
  94. >>> r2.article_set.count()
  95. 1
  96. Note that in the last example the article has moved from John to Paul.
  97. Related managers support field lookups as well.
  98. The API automatically follows relationships as far as you need.
  99. Use double underscores to separate relationships.
  100. This works as many levels deep as you want. There's no limit. For example:
  101. .. code-block:: pycon
  102. >>> r.article_set.filter(headline__startswith="This")
  103. <QuerySet [<Article: This is a test>]>
  104. # Find all Articles for any Reporter whose first name is "John".
  105. >>> Article.objects.filter(reporter__first_name="John")
  106. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  107. Exact match is implied here:
  108. .. code-block:: pycon
  109. >>> Article.objects.filter(reporter__first_name="John")
  110. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  111. Query twice over the related field. This translates to an AND condition in the
  112. WHERE clause:
  113. .. code-block:: pycon
  114. >>> Article.objects.filter(reporter__first_name="John", reporter__last_name="Smith")
  115. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  116. For the related lookup you can supply a primary key value or pass the related
  117. object explicitly:
  118. .. code-block:: pycon
  119. >>> Article.objects.filter(reporter__pk=1)
  120. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  121. >>> Article.objects.filter(reporter=1)
  122. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  123. >>> Article.objects.filter(reporter=r)
  124. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  125. >>> Article.objects.filter(reporter__in=[1, 2]).distinct()
  126. <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
  127. >>> Article.objects.filter(reporter__in=[r, r2]).distinct()
  128. <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
  129. You can also use a queryset instead of a literal list of instances:
  130. .. code-block:: pycon
  131. >>> Article.objects.filter(
  132. ... reporter__in=Reporter.objects.filter(first_name="John")
  133. ... ).distinct()
  134. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  135. Querying in the opposite direction:
  136. .. code-block:: pycon
  137. >>> Reporter.objects.filter(article__pk=1)
  138. <QuerySet [<Reporter: John Smith>]>
  139. >>> Reporter.objects.filter(article=1)
  140. <QuerySet [<Reporter: John Smith>]>
  141. >>> Reporter.objects.filter(article=a)
  142. <QuerySet [<Reporter: John Smith>]>
  143. >>> Reporter.objects.filter(article__headline__startswith="This")
  144. <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
  145. >>> Reporter.objects.filter(article__headline__startswith="This").distinct()
  146. <QuerySet [<Reporter: John Smith>]>
  147. Counting in the opposite direction works in conjunction with ``distinct()``:
  148. .. code-block:: pycon
  149. >>> Reporter.objects.filter(article__headline__startswith="This").count()
  150. 3
  151. >>> Reporter.objects.filter(article__headline__startswith="This").distinct().count()
  152. 1
  153. Queries can go round in circles:
  154. .. code-block:: pycon
  155. >>> Reporter.objects.filter(article__reporter__first_name__startswith="John")
  156. <QuerySet [<Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>, <Reporter: John Smith>]>
  157. >>> Reporter.objects.filter(article__reporter__first_name__startswith="John").distinct()
  158. <QuerySet [<Reporter: John Smith>]>
  159. >>> Reporter.objects.filter(article__reporter=r).distinct()
  160. <QuerySet [<Reporter: John Smith>]>
  161. If you delete a reporter, their articles will be deleted (assuming that the
  162. ForeignKey was defined with :attr:`django.db.models.ForeignKey.on_delete` set to
  163. ``CASCADE``, which is the default):
  164. .. code-block:: pycon
  165. >>> Article.objects.all()
  166. <QuerySet [<Article: John's second story>, <Article: Paul's story>, <Article: This is a test>]>
  167. >>> Reporter.objects.order_by("first_name")
  168. <QuerySet [<Reporter: John Smith>, <Reporter: Paul Jones>]>
  169. >>> r2.delete()
  170. >>> Article.objects.all()
  171. <QuerySet [<Article: John's second story>, <Article: This is a test>]>
  172. >>> Reporter.objects.order_by("first_name")
  173. <QuerySet [<Reporter: John Smith>]>
  174. You can delete using a JOIN in the query:
  175. .. code-block:: pycon
  176. >>> Reporter.objects.filter(article__headline__startswith="This").delete()
  177. >>> Reporter.objects.all()
  178. <QuerySet []>
  179. >>> Article.objects.all()
  180. <QuerySet []>