Commit ffe21e1f authored by Jacob Kaplan-Moss's avatar Jacob Kaplan-Moss
Browse files

Merge pull request #1560 from technivore/ticket_20970

Related Fields documentation improvements
parents b69d1eac a5bcc09c
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.