relations.txt 9.4 KB

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