many_to_one.txt 6.9 KB

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