many_to_one.txt 7.4 KB

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