relations.txt 9.7 KB

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