44
44
>>> e = Entry.objects.get(id=234)
45
45
>>> b.entry_set.add(e) # Associates Entry e with Blog b.
47
In the example above, ``e.save()`` is called to perform the update.
48
Using ``add()`` with a many-to-many relationship, however, will not
49
call any ``save()`` methods, but rather create the relationships
50
using :meth:`QuerySet.bulk_create()
51
<django.db.models.query.QuerySet.bulk_create>`. If you need to execute
52
some custom logic when a relationship is created, listen to the
53
:data:`~django.db.models.signals.m2m_changed` signal.
47
55
.. method:: create(**kwargs)
49
57
Creates a new object, saves it and puts it in the related object set.
82
90
>>> e = Entry.objects.get(id=234)
83
91
>>> b.entry_set.remove(e) # Disassociates Entry e from Blog b.
85
In order to prevent database inconsistency, this method only exists on
86
:class:`~django.db.models.ForeignKey` objects where ``null=True``. If
87
the related field can't be set to ``None`` (``NULL``), then an object
88
can't be removed from a relation without being added to another. In the
89
above example, removing ``e`` from ``b.entry_set()`` is equivalent to
90
doing ``e.blog = None``, and because the ``blog``
91
:class:`~django.db.models.ForeignKey` doesn't have ``null=True``, this
93
Similar to :meth:`add()`, ``e.save()`` is called in the example above
94
to perform the update. Using ``remove()`` with a many-to-many
95
relationship, however, will delete the relationships using
96
:meth:`QuerySet.delete()<django.db.models.query.QuerySet.delete>` which
97
means no model ``save()`` methods are called; listen to the
98
:data:`~django.db.models.signals.m2m_changed` signal if you wish to
99
execute custom code when a relationship is deleted.
101
For :class:`~django.db.models.ForeignKey` objects, this method only
102
exists if ``null=True``. If the related field can't be set to ``None``
103
(``NULL``), then an object can't be removed from a relation without
104
being added to another. In the above example, removing ``e`` from
105
``b.entry_set()`` is equivalent to doing ``e.blog = None``, and because
106
the ``blog`` :class:`~django.db.models.ForeignKey` doesn't have
107
``null=True``, this is invalid.
94
109
.. method:: clear()