relations.txt 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179
  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)
  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. .. method:: create(**kwargs)
  49. Creates a new object, saves it and puts it in the related object set.
  50. Returns the newly created object::
  51. >>> b = Blog.objects.get(id=1)
  52. >>> e = b.entry_set.create(
  53. ... headline='Hello',
  54. ... body_text='Hi',
  55. ... pub_date=datetime.date(2005, 1, 1)
  56. ... )
  57. # No need to call e.save() at this point -- it's already been saved.
  58. This is equivalent to (but much simpler than)::
  59. >>> b = Blog.objects.get(id=1)
  60. >>> e = Entry(
  61. ... blog=b,
  62. ... headline='Hello',
  63. ... body_text='Hi',
  64. ... pub_date=datetime.date(2005, 1, 1)
  65. ... )
  66. >>> e.save(force_insert=True)
  67. Note that there's no need to specify the keyword argument of the model
  68. that defines the relationship. In the above example, we don't pass the
  69. parameter ``blog`` to ``create()``. Django figures out that the new
  70. ``Entry`` object's ``blog`` field should be set to ``b``.
  71. .. method:: remove(*objs)
  72. Removes the specified model objects from the related object set::
  73. >>> b = Blog.objects.get(id=1)
  74. >>> e = Entry.objects.get(id=234)
  75. >>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.
  76. Similar to :meth:`add()`, ``e.save()`` is called in the example above
  77. to perform the update. Using ``remove()`` with a many-to-many
  78. relationship, however, will delete the relationships using
  79. :meth:`QuerySet.delete()<django.db.models.query.QuerySet.delete>` which
  80. means no model ``save()`` methods are called; listen to the
  81. :data:`~django.db.models.signals.m2m_changed` signal if you wish to
  82. execute custom code when a relationship is deleted.
  83. For :class:`~django.db.models.ForeignKey` objects, this method only
  84. exists if ``null=True``. If the related field can't be set to ``None``
  85. (``NULL``), then an object can't be removed from a relation without
  86. being added to another. In the above example, removing ``e`` from
  87. ``b.entry_set()`` is equivalent to doing ``e.blog = None``, and because
  88. the ``blog`` :class:`~django.db.models.ForeignKey` doesn't have
  89. ``null=True``, this is invalid.
  90. For :class:`~django.db.models.ForeignKey` objects, this method accepts
  91. a ``bulk`` argument to control how to perform the operation.
  92. If ``True`` (the default), ``QuerySet.update()`` is used.
  93. If ``bulk=False``, the ``save()`` method of each individual model
  94. instance is called instead. This triggers the
  95. :data:`~django.db.models.signals.pre_save` and
  96. :data:`~django.db.models.signals.post_save` signals and comes at the
  97. expense of performance.
  98. .. method:: clear()
  99. Removes all objects from the related object set::
  100. >>> b = Blog.objects.get(id=1)
  101. >>> b.entry_set.clear()
  102. Note this doesn't delete the related objects -- it just disassociates
  103. them.
  104. Just like ``remove()``, ``clear()`` is only available on
  105. :class:`~django.db.models.ForeignKey`\s where ``null=True`` and it also
  106. accepts the ``bulk`` keyword argument.
  107. .. method:: set(objs, bulk=True, clear=False)
  108. Replace the set of related objects::
  109. >>> new_list = [obj1, obj2, obj3]
  110. >>> e.related_set.set(new_list)
  111. This method accepts a ``clear`` argument to control how to perform the
  112. operation. If ``False`` (the default), the elements missing from the
  113. new set are removed using ``remove()`` and only the new ones are added.
  114. If ``clear=True``, the ``clear()`` method is called instead and the
  115. whole set is added at once.
  116. The ``bulk`` argument is passed on to :meth:`add`.
  117. Note that since ``set()`` is a compound operation, it is subject to
  118. race conditions. For instance, new objects may be added to the database
  119. in between the call to ``clear()`` and the call to ``add()``.
  120. .. note::
  121. Note that ``add()``, ``create()``, ``remove()``, ``clear()``, and
  122. ``set()`` all apply database changes immediately for all types of
  123. related fields. In other words, there is no need to call ``save()``
  124. on either end of the relationship.
  125. Also, if you are using :ref:`an intermediate model
  126. <intermediary-manytomany>` for a many-to-many relationship, then the
  127. ``add()``, ``create()``, ``remove()``, and ``set()`` methods are
  128. disabled.
  129. If you use :meth:`~django.db.models.query.QuerySet.prefetch_related`,
  130. the ``add()``, ``remove()``, ``clear()``, and ``set()`` methods clear
  131. the prefetched cache.