relations.txt 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. =========================
  2. Related objects reference
  3. =========================
  4. .. currentmodule:: django.db.models.fields.related
  5. .. class:: RelatedManager
  6. A "related manager" is a manager used in a one-to-many or many-to-many
  7. related context. This happens in two cases:
  8. * The "other side" of a :class:`~django.db.models.ForeignKey` relation.
  9. That is::
  10. from django.db import models
  11. class Reporter(models.Model):
  12. # ...
  13. pass
  14. class Article(models.Model):
  15. reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE)
  16. In the above example, the methods below will be available on
  17. the manager ``reporter.article_set``.
  18. * Both sides of a :class:`~django.db.models.ManyToManyField` relation::
  19. class Topping(models.Model):
  20. # ...
  21. pass
  22. class Pizza(models.Model):
  23. toppings = models.ManyToManyField(Topping)
  24. In this example, the methods below will be available both on
  25. ``topping.pizza_set`` and on ``pizza.toppings``.
  26. .. method:: add(*objs, bulk=True, through_defaults=None)
  27. Adds the specified model objects to the related object set.
  28. Example::
  29. >>> b = Blog.objects.get(id=1)
  30. >>> e = Entry.objects.get(id=234)
  31. >>> b.entry_set.add(e) # Associates Entry e with Blog b.
  32. In the example above, in the case of a
  33. :class:`~django.db.models.ForeignKey` relationship,
  34. :meth:`QuerySet.update() <django.db.models.query.QuerySet.update>`
  35. is used to perform the update. This requires the objects to already be
  36. saved.
  37. You can use the ``bulk=False`` argument to instead have the related
  38. manager perform the update by calling ``e.save()``.
  39. Using ``add()`` with a many-to-many relationship, however, will not
  40. call any ``save()`` methods (the ``bulk`` argument doesn't exist), but
  41. rather create the relationships using :meth:`QuerySet.bulk_create()
  42. <django.db.models.query.QuerySet.bulk_create>`. If you need to execute
  43. some custom logic when a relationship is created, listen to the
  44. :data:`~django.db.models.signals.m2m_changed` signal, which will
  45. trigger ``pre_add`` and ``post_add`` actions.
  46. Using ``add()`` on a relation that already exists won't duplicate the
  47. relation, but it will still trigger signals.
  48. ``add()`` also accepts the field the relation points to as an argument.
  49. The above example can be rewritten as ``b.entry_set.add(234)``.
  50. Use the ``through_defaults`` argument to specify values for the new
  51. :ref:`intermediate model <intermediary-manytomany>` instance(s), if
  52. needed.
  53. .. versionchanged:: 2.2
  54. The ``through_defaults`` argument was added.
  55. .. method:: create(through_defaults=None, **kwargs)
  56. Creates a new object, saves it and puts it in the related object set.
  57. Returns the newly created object::
  58. >>> b = Blog.objects.get(id=1)
  59. >>> e = b.entry_set.create(
  60. ... headline='Hello',
  61. ... body_text='Hi',
  62. ... pub_date=datetime.date(2005, 1, 1)
  63. ... )
  64. # No need to call e.save() at this point -- it's already been saved.
  65. This is equivalent to (but simpler than)::
  66. >>> b = Blog.objects.get(id=1)
  67. >>> e = Entry(
  68. ... blog=b,
  69. ... headline='Hello',
  70. ... body_text='Hi',
  71. ... pub_date=datetime.date(2005, 1, 1)
  72. ... )
  73. >>> e.save(force_insert=True)
  74. Note that there's no need to specify the keyword argument of the model
  75. that defines the relationship. In the above example, we don't pass the
  76. parameter ``blog`` to ``create()``. Django figures out that the new
  77. ``Entry`` object's ``blog`` field should be set to ``b``.
  78. Use the ``through_defaults`` argument to specify values for the new
  79. :ref:`intermediate model <intermediary-manytomany>` instance, if
  80. needed.
  81. .. versionchanged:: 2.2
  82. The ``through_defaults`` argument was added.
  83. .. method:: remove(*objs, bulk=True)
  84. Removes the specified model objects from the related object set::
  85. >>> b = Blog.objects.get(id=1)
  86. >>> e = Entry.objects.get(id=234)
  87. >>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.
  88. Similar to :meth:`add()`, ``e.save()`` is called in the example above
  89. to perform the update. Using ``remove()`` with a many-to-many
  90. relationship, however, will delete the relationships using
  91. :meth:`QuerySet.delete()<django.db.models.query.QuerySet.delete>` which
  92. means no model ``save()`` methods are called; listen to the
  93. :data:`~django.db.models.signals.m2m_changed` signal if you wish to
  94. execute custom code when a relationship is deleted.
  95. Similarly to :meth:`add()`, ``remove()`` also accepts the field the
  96. relation points to as an argument. The above example can be rewritten
  97. as ``b.entry_set.remove(234)``.
  98. For :class:`~django.db.models.ForeignKey` objects, this method only
  99. exists if ``null=True``. If the related field can't be set to ``None``
  100. (``NULL``), then an object can't be removed from a relation without
  101. being added to another. In the above example, removing ``e`` from
  102. ``b.entry_set()`` is equivalent to doing ``e.blog = None``, and because
  103. the ``blog`` :class:`~django.db.models.ForeignKey` doesn't have
  104. ``null=True``, this is invalid.
  105. For :class:`~django.db.models.ForeignKey` objects, this method accepts
  106. a ``bulk`` argument to control how to perform the operation.
  107. If ``True`` (the default), ``QuerySet.update()`` is used.
  108. If ``bulk=False``, the ``save()`` method of each individual model
  109. instance is called instead. This triggers the
  110. :data:`~django.db.models.signals.pre_save` and
  111. :data:`~django.db.models.signals.post_save` signals and comes at the
  112. expense of performance.
  113. For many-to-many relationships, the ``bulk`` keyword argument doesn't
  114. exist.
  115. .. method:: clear(bulk=True)
  116. Removes all objects from the related object set::
  117. >>> b = Blog.objects.get(id=1)
  118. >>> b.entry_set.clear()
  119. Note this doesn't delete the related objects -- it just disassociates
  120. them.
  121. Just like ``remove()``, ``clear()`` is only available on
  122. :class:`~django.db.models.ForeignKey`\s where ``null=True`` and it also
  123. accepts the ``bulk`` keyword argument.
  124. For many-to-many relationships, the ``bulk`` keyword argument doesn't
  125. exist.
  126. .. method:: set(objs, bulk=True, clear=False, through_defaults=None)
  127. Replace the set of related objects::
  128. >>> new_list = [obj1, obj2, obj3]
  129. >>> e.related_set.set(new_list)
  130. This method accepts a ``clear`` argument to control how to perform the
  131. operation. If ``False`` (the default), the elements missing from the
  132. new set are removed using ``remove()`` and only the new ones are added.
  133. If ``clear=True``, the ``clear()`` method is called instead and the
  134. whole set is added at once.
  135. For :class:`~django.db.models.ForeignKey` objects, the ``bulk``
  136. argument is passed on to :meth:`add` and :meth:`remove`.
  137. For many-to-many relationships, the ``bulk`` keyword argument doesn't
  138. exist.
  139. Note that since ``set()`` is a compound operation, it is subject to
  140. race conditions. For instance, new objects may be added to the database
  141. in between the call to ``clear()`` and the call to ``add()``.
  142. Similarly to :meth:`add()`, ``set()`` also accepts the field the
  143. relation points to as an argument. The above example can be rewritten
  144. as ``e.related_set.set([obj1.pk, obj2.pk, obj3.pk])``.
  145. Use the ``through_defaults`` argument to specify values for the new
  146. :ref:`intermediate model <intermediary-manytomany>` instance(s), if
  147. needed.
  148. .. versionchanged:: 2.2
  149. The ``through_defaults`` argument was added.
  150. .. note::
  151. Note that ``add()``, ``create()``, ``remove()``, ``clear()``, and
  152. ``set()`` all apply database changes immediately for all types of
  153. related fields. In other words, there is no need to call ``save()``
  154. on either end of the relationship.
  155. If you use :meth:`~django.db.models.query.QuerySet.prefetch_related`,
  156. the ``add()``, ``remove()``, ``clear()``, and ``set()`` methods clear
  157. the prefetched cache.