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