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