relations.txt 7.1 KB

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