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