Commit a5bcc09c authored by Matthew Rich's avatar Matthew Rich
Browse files

documented RelatedManager calling save() behind the scenes, added section on...

documented RelatedManager calling save() behind the scenes, added section on direct replacement of related object set
parent a91799a3
Loading
Loading
Loading
Loading
+92 −64
Original line number Diff line number Diff line
@@ -36,7 +36,10 @@ Related objects reference
      In this example, the methods below will be available both on
      ``topping.pizza_set`` and on ``pizza.toppings``.

    These related managers have some extra methods:
.. _related-manager-methods:

Related Manager Methods
-----------------------

.. method:: add(obj1, [obj2, ...])

@@ -48,7 +51,9 @@ Related objects reference
        >>> e = Entry.objects.get(id=234)
        >>> b.entry_set.add(e) # Associates Entry e with Blog b.

        In the example above, ``e.save()`` is called to perform the update.
    In the example above, in the case of a
    :class:`~django.db.models.ForeignKey` relationship,
    ``e.save()`` is called by the related manager to perform the update.
    Using ``add()`` with a many-to-many relationship, however, will not
    call any ``save()`` methods, but rather create the relationships
    using :meth:`QuerySet.bulk_create()
@@ -122,3 +127,26 @@ Related objects reference

    Just like ``remove()``, ``clear()`` is only available on
    :class:`~django.db.models.ForeignKey`\s where ``null=True``.

.. note::

   Note that ``add()``, ``create()``, ``remove()``, and ``clear()`` all
   apply database changes immediately for all types of related fields. In other
   words, there is no need to call ``save()`` on either end of the
   relationship.

.. _direct-assignment:

Direct Assignment
-----------------

A related object set can be replaced in bulk with one operation by assigning a
new iterable of objects to it::

    >>> new_list = [obj1, obj2, obj3]
    >>> e.related_set = new_list 

If the foreign key relationship has ``null=True``, then the related manager
will first call ``clear()`` to disassociate any existing objects in the related
set before adding the contents of ``new_list``. Otherwise the objects in
``new_list`` will be added to the existing related object set.