relations.txt 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  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. For many-to-many relationships ``add()`` accepts either model instances
  49. or field values, normally primary keys, as the ``*objs`` argument.
  50. Use the ``through_defaults`` argument to specify values for the new
  51. :ref:`intermediate model <intermediary-manytomany>` instance(s), if
  52. needed. You can use callables as values in the ``through_defaults``
  53. dictionary and they will be evaluated once before creating any
  54. intermediate instance(s).
  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. You can use callables as values in the ``through_defaults``
  81. dictionary.
  82. .. method:: remove(*objs, bulk=True)
  83. Removes the specified model objects from the related object set::
  84. >>> b = Blog.objects.get(id=1)
  85. >>> e = Entry.objects.get(id=234)
  86. >>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.
  87. Similar to :meth:`add()`, ``e.save()`` is called in the example above
  88. to perform the update. Using ``remove()`` with a many-to-many
  89. relationship, however, will delete the relationships using
  90. :meth:`QuerySet.delete()<django.db.models.query.QuerySet.delete>` which
  91. means no model ``save()`` methods are called; listen to the
  92. :data:`~django.db.models.signals.m2m_changed` signal if you wish to
  93. execute custom code when a relationship is deleted.
  94. For many-to-many relationships ``remove()`` accepts either model
  95. instances or field values, normally primary keys, as the ``*objs``
  96. argument.
  97. For :class:`~django.db.models.ForeignKey` objects, this method only
  98. exists if ``null=True``. If the related field can't be set to ``None``
  99. (``NULL``), then an object can't be removed from a relation without
  100. being added to another. In the above example, removing ``e`` from
  101. ``b.entry_set()`` is equivalent to doing ``e.blog = None``, and because
  102. the ``blog`` :class:`~django.db.models.ForeignKey` doesn't have
  103. ``null=True``, this is invalid.
  104. For :class:`~django.db.models.ForeignKey` objects, this method accepts
  105. a ``bulk`` argument to control how to perform the operation.
  106. If ``True`` (the default), ``QuerySet.update()`` is used.
  107. If ``bulk=False``, the ``save()`` method of each individual model
  108. instance is called instead. This triggers the
  109. :data:`~django.db.models.signals.pre_save` and
  110. :data:`~django.db.models.signals.post_save` signals and comes at the
  111. expense of performance.
  112. For many-to-many relationships, the ``bulk`` keyword argument doesn't
  113. exist.
  114. .. method:: clear(bulk=True)
  115. Removes all objects from the related object set::
  116. >>> b = Blog.objects.get(id=1)
  117. >>> b.entry_set.clear()
  118. Note this doesn't delete the related objects -- it just disassociates
  119. them.
  120. Just like ``remove()``, ``clear()`` is only available on
  121. :class:`~django.db.models.ForeignKey`\s where ``null=True`` and it also
  122. accepts the ``bulk`` keyword argument.
  123. For many-to-many relationships, the ``bulk`` keyword argument doesn't
  124. exist.
  125. .. method:: set(objs, bulk=True, clear=False, through_defaults=None)
  126. Replace the set of related objects::
  127. >>> new_list = [obj1, obj2, obj3]
  128. >>> e.related_set.set(new_list)
  129. This method accepts a ``clear`` argument to control how to perform the
  130. operation. If ``False`` (the default), the elements missing from the
  131. new set are removed using ``remove()`` and only the new ones are added.
  132. If ``clear=True``, the ``clear()`` method is called instead and the
  133. whole set is added at once.
  134. For :class:`~django.db.models.ForeignKey` objects, the ``bulk``
  135. argument is passed on to :meth:`add` and :meth:`remove`.
  136. For many-to-many relationships, the ``bulk`` keyword argument doesn't
  137. exist.
  138. Note that since ``set()`` is a compound operation, it is subject to
  139. race conditions. For instance, new objects may be added to the database
  140. in between the call to ``clear()`` and the call to ``add()``.
  141. For many-to-many relationships ``set()`` accepts a list of either model
  142. instances or field values, normally primary keys, as the ``objs``
  143. argument.
  144. Use the ``through_defaults`` argument to specify values for the new
  145. :ref:`intermediate model <intermediary-manytomany>` instance(s), if
  146. needed. You can use callables as values in the ``through_defaults``
  147. dictionary and they will be evaluated once before creating any
  148. intermediate instance(s).
  149. .. note::
  150. Note that ``add()``, ``create()``, ``remove()``, ``clear()``, and
  151. ``set()`` all apply database changes immediately for all types of
  152. related fields. In other words, there is no need to call ``save()``
  153. on either end of the relationship.
  154. If you use :meth:`~django.db.models.query.QuerySet.prefetch_related`,
  155. the ``add()``, ``remove()``, ``clear()``, and ``set()`` methods clear
  156. the prefetched cache.