| 1 |
========================== |
| 2 |
The contenttypes framework |
| 3 |
========================== |
| 4 |
|
| 5 |
.. module:: django.contrib.contenttypes |
| 6 |
:synopsis: Provides generic interface to installed models. |
| 7 |
|
| 8 |
Django includes a :mod:`~django.contrib.contenttypes` application that can |
| 9 |
track all of the models installed in your Django-powered project, providing a |
| 10 |
high-level, generic interface for working with your models. |
| 11 |
|
| 12 |
Overview |
| 13 |
======== |
| 14 |
|
| 15 |
At the heart of the contenttypes application is the |
| 16 |
:class:`~django.contrib.contenttypes.models.ContentType` model, which lives at |
| 17 |
``django.contrib.contenttypes.models.ContentType``. Instances of |
| 18 |
:class:`~django.contrib.contenttypes.models.ContentType` represent and store |
| 19 |
information about the models installed in your project, and new instances of |
| 20 |
:class:`~django.contrib.contenttypes.models.ContentType` are automatically |
| 21 |
created whenever new models are installed. |
| 22 |
|
| 23 |
Instances of :class:`~django.contrib.contenttypes.models.ContentType` have |
| 24 |
methods for returning the model classes they represent and for querying objects |
| 25 |
from those models. :class:`~django.contrib.contenttypes.models.ContentType` |
| 26 |
also has a :ref:`custom manager <custom-managers>` that adds methods for |
| 27 |
working with :class:`~django.contrib.contenttypes.models.ContentType` and for |
| 28 |
obtaining instances of :class:`~django.contrib.contenttypes.models.ContentType` |
| 29 |
for a particular model. |
| 30 |
|
| 31 |
Relations between your models and |
| 32 |
:class:`~django.contrib.contenttypes.models.ContentType` can also be used to |
| 33 |
enable "generic" relationships between an instance of one of your |
| 34 |
models and instances of any model you have installed. |
| 35 |
|
| 36 |
Installing the contenttypes framework |
| 37 |
===================================== |
| 38 |
|
| 39 |
The contenttypes framework is included in the default |
| 40 |
:setting:`INSTALLED_APPS` list created by ``django-admin startproject``, |
| 41 |
but if you've removed it or if you manually set up your |
| 42 |
:setting:`INSTALLED_APPS` list, you can enable it by adding |
| 43 |
``'django.contrib.contenttypes'`` to your :setting:`INSTALLED_APPS` setting. |
| 44 |
|
| 45 |
It's generally a good idea to have the contenttypes framework |
| 46 |
installed; several of Django's other bundled applications require it: |
| 47 |
|
| 48 |
* The admin application uses it to log the history of each object |
| 49 |
added or changed through the admin interface. |
| 50 |
|
| 51 |
* Django's :mod:`authentication framework <django.contrib.auth>` uses it |
| 52 |
to tie user permissions to specific models. |
| 53 |
|
| 54 |
.. currentmodule:: django.contrib.contenttypes.models |
| 55 |
|
| 56 |
The ``ContentType`` model |
| 57 |
========================= |
| 58 |
|
| 59 |
.. class:: ContentType |
| 60 |
|
| 61 |
Each instance of :class:`~django.contrib.contenttypes.models.ContentType` |
| 62 |
has two fields which, taken together, uniquely describe an installed |
| 63 |
model: |
| 64 |
|
| 65 |
.. attribute:: app_label |
| 66 |
|
| 67 |
The name of the application the model is part of. This is taken from |
| 68 |
the :attr:`app_label` attribute of the model, and includes only the |
| 69 |
*last* part of the application's Python import path; |
| 70 |
``django.contrib.contenttypes``, for example, becomes an |
| 71 |
:attr:`app_label` of ``contenttypes``. |
| 72 |
|
| 73 |
.. attribute:: model |
| 74 |
|
| 75 |
The name of the model class. |
| 76 |
|
| 77 |
Additionally, the following property is available: |
| 78 |
|
| 79 |
.. attribute:: name |
| 80 |
|
| 81 |
The human-readable name of the content type. This is taken from the |
| 82 |
:attr:`verbose_name <django.db.models.Field.verbose_name>` |
| 83 |
attribute of the model. |
| 84 |
|
| 85 |
Let's look at an example to see how this works. If you already have |
| 86 |
the :mod:`~django.contrib.contenttypes` application installed, and then add |
| 87 |
:mod:`the sites application <django.contrib.sites>` to your |
| 88 |
:setting:`INSTALLED_APPS` setting and run ``manage.py migrate`` to install it, |
| 89 |
the model :class:`django.contrib.sites.models.Site` will be installed into |
| 90 |
your database. Along with it a new instance of |
| 91 |
:class:`~django.contrib.contenttypes.models.ContentType` will be |
| 92 |
created with the following values: |
| 93 |
|
| 94 |
* :attr:`~django.contrib.contenttypes.models.ContentType.app_label` |
| 95 |
will be set to ``'sites'`` (the last part of the Python |
| 96 |
path ``django.contrib.sites``). |
| 97 |
|
| 98 |
* :attr:`~django.contrib.contenttypes.models.ContentType.model` |
| 99 |
will be set to ``'site'``. |
| 100 |
|
| 101 |
Methods on ``ContentType`` instances |
| 102 |
==================================== |
| 103 |
|
| 104 |
Each :class:`~django.contrib.contenttypes.models.ContentType` instance has |
| 105 |
methods that allow you to get from a |
| 106 |
:class:`~django.contrib.contenttypes.models.ContentType` instance to the |
| 107 |
model it represents, or to retrieve objects from that model: |
| 108 |
|
| 109 |
.. method:: ContentType.get_object_for_this_type(using=None, **kwargs) |
| 110 |
|
| 111 |
Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the |
| 112 |
model the :class:`~django.contrib.contenttypes.models.ContentType` |
| 113 |
represents, and does |
| 114 |
:meth:`a get() lookup <django.db.models.query.QuerySet.get>` |
| 115 |
on that model, returning the corresponding object. The ``using`` argument |
| 116 |
can be used to specify a different database than the default one. |
| 117 |
|
| 118 |
.. versionchanged:: 5.1 |
| 119 |
|
| 120 |
The ``using`` argument was added. |
| 121 |
|
| 122 |
.. method:: ContentType.model_class() |
| 123 |
|
| 124 |
Returns the model class represented by this |
| 125 |
:class:`~django.contrib.contenttypes.models.ContentType` instance. |
| 126 |
|
| 127 |
For example, we could look up the |
| 128 |
:class:`~django.contrib.contenttypes.models.ContentType` for the |
| 129 |
:class:`~django.contrib.auth.models.User` model: |
| 130 |
|
| 131 |
.. code-block:: pycon |
| 132 |
|
| 133 |
>>> from django.contrib.contenttypes.models import ContentType |
| 134 |
>>> user_type = ContentType.objects.get(app_label="auth", model="user") |
| 135 |
>>> user_type |
| 136 |
<ContentType: user> |
| 137 |
|
| 138 |
And then use it to query for a particular |
| 139 |
:class:`~django.contrib.auth.models.User`, or to get access |
| 140 |
to the ``User`` model class: |
| 141 |
|
| 142 |
.. code-block:: pycon |
| 143 |
|
| 144 |
>>> user_type.model_class() |
| 145 |
<class 'django.contrib.auth.models.User'> |
| 146 |
>>> user_type.get_object_for_this_type(username="Guido") |
| 147 |
<User: Guido> |
| 148 |
|
| 149 |
Together, |
| 150 |
:meth:`~django.contrib.contenttypes.models.ContentType.get_object_for_this_type` |
| 151 |
and :meth:`~django.contrib.contenttypes.models.ContentType.model_class` enable |
| 152 |
two extremely important use cases: |
| 153 |
|
| 154 |
1. Using these methods, you can write high-level generic code that |
| 155 |
performs queries on any installed model -- instead of importing and |
| 156 |
using a single specific model class, you can pass an ``app_label`` and |
| 157 |
``model`` into a |
| 158 |
:class:`~django.contrib.contenttypes.models.ContentType` lookup at |
| 159 |
runtime, and then work with the model class or retrieve objects from it. |
| 160 |
|
| 161 |
2. You can relate another model to |
| 162 |
:class:`~django.contrib.contenttypes.models.ContentType` as a way of |
| 163 |
tying instances of it to particular model classes, and use these methods |
| 164 |
to get access to those model classes. |
| 165 |
|
| 166 |
Several of Django's bundled applications make use of the latter technique. |
| 167 |
For example, |
| 168 |
:class:`the permissions system <django.contrib.auth.models.Permission>` in |
| 169 |
Django's authentication framework uses a |
| 170 |
:class:`~django.contrib.auth.models.Permission` model with a foreign |
| 171 |
key to :class:`~django.contrib.contenttypes.models.ContentType`; this lets |
| 172 |
:class:`~django.contrib.auth.models.Permission` represent concepts like |
| 173 |
"can add blog entry" or "can delete news story". |
| 174 |
|
| 175 |
The ``ContentTypeManager`` |
| 176 |
-------------------------- |
| 177 |
|
| 178 |
.. class:: ContentTypeManager |
| 179 |
|
| 180 |
:class:`~django.contrib.contenttypes.models.ContentType` also has a custom |
| 181 |
manager, :class:`~django.contrib.contenttypes.models.ContentTypeManager`, |
| 182 |
which adds the following methods: |
| 183 |
|
| 184 |
.. method:: clear_cache() |
| 185 |
|
| 186 |
Clears an internal cache used by |
| 187 |
:class:`~django.contrib.contenttypes.models.ContentType` to keep track |
| 188 |
of models for which it has created |
| 189 |
:class:`~django.contrib.contenttypes.models.ContentType` instances. You |
| 190 |
probably won't ever need to call this method yourself; Django will call |
| 191 |
it automatically when it's needed. |
| 192 |
|
| 193 |
.. method:: get_for_id(id) |
| 194 |
|
| 195 |
Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by ID. |
| 196 |
Since this method uses the same shared cache as |
| 197 |
:meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`, |
| 198 |
it's preferred to use this method over the usual |
| 199 |
``ContentType.objects.get(pk=id)`` |
| 200 |
|
| 201 |
.. method:: get_for_model(model, for_concrete_model=True) |
| 202 |
|
| 203 |
Takes either a model class or an instance of a model, and returns the |
| 204 |
:class:`~django.contrib.contenttypes.models.ContentType` instance |
| 205 |
representing that model. ``for_concrete_model=False`` allows fetching |
| 206 |
the :class:`~django.contrib.contenttypes.models.ContentType` of a proxy |
| 207 |
model. |
| 208 |
|
| 209 |
.. method:: get_for_models(*models, for_concrete_models=True) |
| 210 |
|
| 211 |
Takes a variadic number of model classes, and returns a dictionary |
| 212 |
mapping the model classes to the |
| 213 |
:class:`~django.contrib.contenttypes.models.ContentType` instances |
| 214 |
representing them. ``for_concrete_models=False`` allows fetching the |
| 215 |
:class:`~django.contrib.contenttypes.models.ContentType` of proxy |
| 216 |
models. |
| 217 |
|
| 218 |
.. method:: get_by_natural_key(app_label, model) |
| 219 |
|
| 220 |
Returns the :class:`~django.contrib.contenttypes.models.ContentType` |
| 221 |
instance uniquely identified by the given application label and model |
| 222 |
name. The primary purpose of this method is to allow |
| 223 |
:class:`~django.contrib.contenttypes.models.ContentType` objects to be |
| 224 |
referenced via a :ref:`natural key<topics-serialization-natural-keys>` |
| 225 |
during deserialization. |
| 226 |
|
| 227 |
The :meth:`~ContentTypeManager.get_for_model()` method is especially |
| 228 |
useful when you know you need to work with a |
| 229 |
:class:`ContentType <django.contrib.contenttypes.models.ContentType>` but don't |
| 230 |
want to go to the trouble of obtaining the model's metadata to perform a manual |
| 231 |
lookup: |
| 232 |
|
| 233 |
.. code-block:: pycon |
| 234 |
|
| 235 |
>>> from django.contrib.auth.models import User |
| 236 |
>>> ContentType.objects.get_for_model(User) |
| 237 |
<ContentType: user> |
| 238 |
|
| 239 |
.. module:: django.contrib.contenttypes.fields |
| 240 |
|
| 241 |
.. _generic-relations: |
| 242 |
|
| 243 |
Generic relations |
| 244 |
================= |
| 245 |
|
| 246 |
Adding a foreign key from one of your own models to |
| 247 |
:class:`~django.contrib.contenttypes.models.ContentType` allows your model to |
| 248 |
effectively tie itself to another model class, as in the example of the |
| 249 |
:class:`~django.contrib.auth.models.Permission` model above. But it's possible |
| 250 |
to go one step further and use |
| 251 |
:class:`~django.contrib.contenttypes.models.ContentType` to enable truly |
| 252 |
generic (sometimes called "polymorphic") relationships between models. |
| 253 |
|
| 254 |
For example, it could be used for a tagging system like so:: |
| 255 |
|
| 256 |
from django.contrib.contenttypes.fields import GenericForeignKey |
| 257 |
from django.contrib.contenttypes.models import ContentType |
| 258 |
from django.db import models |
| 259 |
|
| 260 |
|
| 261 |
class TaggedItem(models.Model): |
| 262 |
tag = models.SlugField() |
| 263 |
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) |
| 264 |
object_id = models.PositiveBigIntegerField() |
| 265 |
content_object = GenericForeignKey("content_type", "object_id") |
| 266 |
|
| 267 |
def __str__(self): |
| 268 |
return self.tag |
| 269 |
|
| 270 |
class Meta: |
| 271 |
indexes = [ |
| 272 |
models.Index(fields=["content_type", "object_id"]), |
| 273 |
] |
| 274 |
|
| 275 |
A normal :class:`~django.db.models.ForeignKey` can only "point |
| 276 |
to" one other model, which means that if the ``TaggedItem`` model used a |
| 277 |
:class:`~django.db.models.ForeignKey` it would have to |
| 278 |
choose one and only one model to store tags for. The contenttypes |
| 279 |
application provides a special field type (``GenericForeignKey``) which |
| 280 |
works around this and allows the relationship to be with any |
| 281 |
model: |
| 282 |
|
| 283 |
.. class:: GenericForeignKey |
| 284 |
|
| 285 |
There are three parts to setting up a |
| 286 |
:class:`~django.contrib.contenttypes.fields.GenericForeignKey`: |
| 287 |
|
| 288 |
1. Give your model a :class:`~django.db.models.ForeignKey` |
| 289 |
to :class:`~django.contrib.contenttypes.models.ContentType`. The usual |
| 290 |
name for this field is "content_type". |
| 291 |
|
| 292 |
2. Give your model a field that can store primary key values from the |
| 293 |
models you'll be relating to. For most models, this means a |
| 294 |
:class:`~django.db.models.PositiveBigIntegerField`. The usual name |
| 295 |
for this field is "object_id". |
| 296 |
|
| 297 |
3. Give your model a |
| 298 |
:class:`~django.contrib.contenttypes.fields.GenericForeignKey`, and |
| 299 |
pass it the names of the two fields described above. If these fields |
| 300 |
are named "content_type" and "object_id", you can omit this -- those |
| 301 |
are the default field names |
| 302 |
:class:`~django.contrib.contenttypes.fields.GenericForeignKey` will |
| 303 |
look for. |
| 304 |
|
| 305 |
Unlike for the :class:`~django.db.models.ForeignKey`, a database index is |
| 306 |
*not* automatically created on the |
| 307 |
:class:`~django.contrib.contenttypes.fields.GenericForeignKey`, so it's |
| 308 |
recommended that you use |
| 309 |
:attr:`Meta.indexes <django.db.models.Options.indexes>` to add your own |
| 310 |
multiple column index. This behavior :ticket:`may change <23435>` in the |
| 311 |
future. |
| 312 |
|
| 313 |
.. attribute:: GenericForeignKey.for_concrete_model |
| 314 |
|
| 315 |
If ``False``, the field will be able to reference proxy models. Default |
| 316 |
is ``True``. This mirrors the ``for_concrete_model`` argument to |
| 317 |
:meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`. |
| 318 |
|
| 319 |
.. admonition:: Primary key type compatibility |
| 320 |
|
| 321 |
The "object_id" field doesn't have to be the same type as the |
| 322 |
primary key fields on the related models, but their primary key values |
| 323 |
must be coercible to the same type as the "object_id" field by its |
| 324 |
:meth:`~django.db.models.Field.get_db_prep_value` method. |
| 325 |
|
| 326 |
For example, if you want to allow generic relations to models with either |
| 327 |
:class:`~django.db.models.IntegerField` or |
| 328 |
:class:`~django.db.models.CharField` primary key fields, you |
| 329 |
can use :class:`~django.db.models.CharField` for the |
| 330 |
"object_id" field on your model since integers can be coerced to |
| 331 |
strings by :meth:`~django.db.models.Field.get_db_prep_value`. |
| 332 |
|
| 333 |
For maximum flexibility you can use a |
| 334 |
:class:`~django.db.models.TextField` which doesn't have a |
| 335 |
maximum length defined, however this may incur significant performance |
| 336 |
penalties depending on your database backend. |
| 337 |
|
| 338 |
There is no one-size-fits-all solution for which field type is best. You |
| 339 |
should evaluate the models you expect to be pointing to and determine |
| 340 |
which solution will be most effective for your use case. |
| 341 |
|
| 342 |
.. admonition:: Serializing references to ``ContentType`` objects |
| 343 |
|
| 344 |
If you're serializing data (for example, when generating |
| 345 |
:class:`~django.test.TransactionTestCase.fixtures`) from a model that implements |
| 346 |
generic relations, you should probably be using a natural key to uniquely |
| 347 |
identify related :class:`~django.contrib.contenttypes.models.ContentType` |
| 348 |
objects. See :ref:`natural keys<topics-serialization-natural-keys>` and |
| 349 |
:option:`dumpdata --natural-foreign` for more information. |
| 350 |
|
| 351 |
This will enable an API similar to the one used for a normal |
| 352 |
:class:`~django.db.models.ForeignKey`; |
| 353 |
each ``TaggedItem`` will have a ``content_object`` field that returns the |
| 354 |
object it's related to, and you can also assign to that field or use it when |
| 355 |
creating a ``TaggedItem``: |
| 356 |
|
| 357 |
.. code-block:: pycon |
| 358 |
|
| 359 |
>>> from django.contrib.auth.models import User |
| 360 |
>>> guido = User.objects.get(username="Guido") |
| 361 |
>>> t = TaggedItem(content_object=guido, tag="bdfl") |
| 362 |
>>> t.save() |
| 363 |
>>> t.content_object |
| 364 |
<User: Guido> |
| 365 |
|
| 366 |
If the related object is deleted, the ``content_type`` and ``object_id`` fields |
| 367 |
remain set to their original values and the ``GenericForeignKey`` returns |
| 368 |
``None``: |
| 369 |
|
| 370 |
.. code-block:: pycon |
| 371 |
|
| 372 |
>>> guido.delete() |
| 373 |
>>> t.content_object # returns None |
| 374 |
|
| 375 |
Due to the way :class:`~django.contrib.contenttypes.fields.GenericForeignKey` |
| 376 |
is implemented, you cannot use such fields directly with filters (``filter()`` |
| 377 |
and ``exclude()``, for example) via the database API. Because a |
| 378 |
:class:`~django.contrib.contenttypes.fields.GenericForeignKey` isn't a |
| 379 |
normal field object, these examples will *not* work: |
| 380 |
|
| 381 |
.. code-block:: pycon |
| 382 |
|
| 383 |
# This will fail |
| 384 |
>>> TaggedItem.objects.filter(content_object=guido) |
| 385 |
# This will also fail |
| 386 |
>>> TaggedItem.objects.get(content_object=guido) |
| 387 |
|
| 388 |
Likewise, :class:`~django.contrib.contenttypes.fields.GenericForeignKey`\s |
| 389 |
do not appear in :class:`~django.forms.ModelForm`\s. |
| 390 |
|
| 391 |
Reverse generic relations |
| 392 |
------------------------- |
| 393 |
|
| 394 |
.. class:: GenericRelation |
| 395 |
|
| 396 |
.. attribute:: related_query_name |
| 397 |
|
| 398 |
The relation on the related object back to this object doesn't exist by |
| 399 |
default. Setting ``related_query_name`` creates a relation from the |
| 400 |
related object back to this one. This allows querying and filtering |
| 401 |
from the related object. |
| 402 |
|
| 403 |
If you know which models you'll be using most often, you can also add |
| 404 |
a "reverse" generic relationship to enable an additional API. For example:: |
| 405 |
|
| 406 |
from django.contrib.contenttypes.fields import GenericRelation |
| 407 |
from django.db import models |
| 408 |
|
| 409 |
|
| 410 |
class Bookmark(models.Model): |
| 411 |
url = models.URLField() |
| 412 |
tags = GenericRelation(TaggedItem) |
| 413 |
|
| 414 |
``Bookmark`` instances will each have a ``tags`` attribute, which can |
| 415 |
be used to retrieve their associated ``TaggedItems``: |
| 416 |
|
| 417 |
.. code-block:: pycon |
| 418 |
|
| 419 |
>>> b = Bookmark(url="https://www.djangoproject.com/") |
| 420 |
>>> b.save() |
| 421 |
>>> t1 = TaggedItem(content_object=b, tag="django") |
| 422 |
>>> t1.save() |
| 423 |
>>> t2 = TaggedItem(content_object=b, tag="python") |
| 424 |
>>> t2.save() |
| 425 |
>>> b.tags.all() |
| 426 |
<QuerySet [<TaggedItem: django>, <TaggedItem: python>]> |
| 427 |
|
| 428 |
You can also use ``add()``, ``create()``, or ``set()`` to create |
| 429 |
relationships: |
| 430 |
|
| 431 |
.. code-block:: pycon |
| 432 |
|
| 433 |
>>> t3 = TaggedItem(tag="Web development") |
| 434 |
>>> b.tags.add(t3, bulk=False) |
| 435 |
>>> b.tags.create(tag="Web framework") |
| 436 |
<TaggedItem: Web framework> |
| 437 |
>>> b.tags.all() |
| 438 |
<QuerySet [<TaggedItem: django>, <TaggedItem: python>, <TaggedItem: Web development>, <TaggedItem: Web framework>]> |
| 439 |
>>> b.tags.set([t1, t3]) |
| 440 |
>>> b.tags.all() |
| 441 |
<QuerySet [<TaggedItem: django>, <TaggedItem: Web development>]> |
| 442 |
|
| 443 |
The ``remove()`` call will bulk delete the specified model objects: |
| 444 |
|
| 445 |
.. code-block:: pycon |
| 446 |
|
| 447 |
>>> b.tags.remove(t3) |
| 448 |
>>> b.tags.all() |
| 449 |
<QuerySet [<TaggedItem: django>]> |
| 450 |
>>> TaggedItem.objects.all() |
| 451 |
<QuerySet [<TaggedItem: django>]> |
| 452 |
|
| 453 |
The ``clear()`` method can be used to bulk delete all related objects for an |
| 454 |
instance: |
| 455 |
|
| 456 |
.. code-block:: pycon |
| 457 |
|
| 458 |
>>> b.tags.clear() |
| 459 |
>>> b.tags.all() |
| 460 |
<QuerySet []> |
| 461 |
>>> TaggedItem.objects.all() |
| 462 |
<QuerySet []> |
| 463 |
|
| 464 |
Defining :class:`~django.contrib.contenttypes.fields.GenericRelation` with |
| 465 |
``related_query_name`` set allows querying from the related object:: |
| 466 |
|
| 467 |
tags = GenericRelation(TaggedItem, related_query_name="bookmark") |
| 468 |
|
| 469 |
This enables filtering, ordering, and other query operations on ``Bookmark`` |
| 470 |
from ``TaggedItem``: |
| 471 |
|
| 472 |
.. code-block:: pycon |
| 473 |
|
| 474 |
>>> # Get all tags belonging to bookmarks containing `django` in the url |
| 475 |
>>> TaggedItem.objects.filter(bookmark__url__contains="django") |
| 476 |
<QuerySet [<TaggedItem: django>, <TaggedItem: python>]> |
| 477 |
|
| 478 |
If you don't add the ``related_query_name``, you can do the same types of |
| 479 |
lookups manually: |
| 480 |
|
| 481 |
.. code-block:: pycon |
| 482 |
|
| 483 |
>>> bookmarks = Bookmark.objects.filter(url__contains="django") |
| 484 |
>>> bookmark_type = ContentType.objects.get_for_model(Bookmark) |
| 485 |
>>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id, object_id__in=bookmarks) |
| 486 |
<QuerySet [<TaggedItem: django>, <TaggedItem: python>]> |
| 487 |
|
| 488 |
Just as :class:`~django.contrib.contenttypes.fields.GenericForeignKey` |
| 489 |
accepts the names of the content-type and object-ID fields as |
| 490 |
arguments, so too does |
| 491 |
:class:`~django.contrib.contenttypes.fields.GenericRelation`; |
| 492 |
if the model which has the generic foreign key is using non-default names |
| 493 |
for those fields, you must pass the names of the fields when setting up a |
| 494 |
:class:`.GenericRelation` to it. For example, if the ``TaggedItem`` model |
| 495 |
referred to above used fields named ``content_type_fk`` and |
| 496 |
``object_primary_key`` to create its generic foreign key, then a |
| 497 |
:class:`.GenericRelation` back to it would need to be defined like so:: |
| 498 |
|
| 499 |
tags = GenericRelation( |
| 500 |
TaggedItem, |
| 501 |
content_type_field="content_type_fk", |
| 502 |
object_id_field="object_primary_key", |
| 503 |
) |
| 504 |
|
| 505 |
Note also, that if you delete an object that has a |
| 506 |
:class:`~django.contrib.contenttypes.fields.GenericRelation`, any objects |
| 507 |
which have a :class:`~django.contrib.contenttypes.fields.GenericForeignKey` |
| 508 |
pointing at it will be deleted as well. In the example above, this means that |
| 509 |
if a ``Bookmark`` object were deleted, any ``TaggedItem`` objects pointing at |
| 510 |
it would be deleted at the same time. |
| 511 |
|
| 512 |
Unlike :class:`~django.db.models.ForeignKey`, |
| 513 |
:class:`~django.contrib.contenttypes.fields.GenericForeignKey` does not accept |
| 514 |
an :attr:`~django.db.models.ForeignKey.on_delete` argument to customize this |
| 515 |
behavior; if desired, you can avoid the cascade-deletion by not using |
| 516 |
:class:`~django.contrib.contenttypes.fields.GenericRelation`, and alternate |
| 517 |
behavior can be provided via the :data:`~django.db.models.signals.pre_delete` |
| 518 |
signal. |
| 519 |
|
| 520 |
Generic relations and aggregation |
| 521 |
--------------------------------- |
| 522 |
|
| 523 |
:doc:`Django's database aggregation API </topics/db/aggregation>` works with a |
| 524 |
:class:`~django.contrib.contenttypes.fields.GenericRelation`. For example, you |
| 525 |
can find out how many tags all the bookmarks have: |
| 526 |
|
| 527 |
.. code-block:: pycon |
| 528 |
|
| 529 |
>>> Bookmark.objects.aggregate(Count("tags")) |
| 530 |
{'tags__count': 3} |
| 531 |
|
| 532 |
.. module:: django.contrib.contenttypes.forms |
| 533 |
|
| 534 |
Generic relation in forms |
| 535 |
------------------------- |
| 536 |
|
| 537 |
The :mod:`django.contrib.contenttypes.forms` module provides: |
| 538 |
|
| 539 |
* :class:`BaseGenericInlineFormSet` |
| 540 |
* A formset factory, :func:`generic_inlineformset_factory`, for use with |
| 541 |
:class:`~django.contrib.contenttypes.fields.GenericForeignKey`. |
| 542 |
|
| 543 |
.. class:: BaseGenericInlineFormSet |
| 544 |
|
| 545 |
.. function:: generic_inlineformset_factory(model, form=ModelForm, formset=BaseGenericInlineFormSet, ct_field="content_type", fk_field="object_id", fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False, absolute_max=None, can_delete_extra=True) |
| 546 |
|
| 547 |
Returns a ``GenericInlineFormSet`` using |
| 548 |
:func:`~django.forms.models.modelformset_factory`. |
| 549 |
|
| 550 |
You must provide ``ct_field`` and ``fk_field`` if they are different from |
| 551 |
the defaults, ``content_type`` and ``object_id`` respectively. Other |
| 552 |
parameters are similar to those documented in |
| 553 |
:func:`~django.forms.models.modelformset_factory` and |
| 554 |
:func:`~django.forms.models.inlineformset_factory`. |
| 555 |
|
| 556 |
The ``for_concrete_model`` argument corresponds to the |
| 557 |
:class:`~django.contrib.contenttypes.fields.GenericForeignKey.for_concrete_model` |
| 558 |
argument on ``GenericForeignKey``. |
| 559 |
|
| 560 |
.. module:: django.contrib.contenttypes.admin |
| 561 |
|
| 562 |
Generic relations in admin |
| 563 |
-------------------------- |
| 564 |
|
| 565 |
The :mod:`django.contrib.contenttypes.admin` module provides |
| 566 |
:class:`~django.contrib.contenttypes.admin.GenericTabularInline` and |
| 567 |
:class:`~django.contrib.contenttypes.admin.GenericStackedInline` (subclasses of |
| 568 |
:class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`) |
| 569 |
|
| 570 |
These classes and functions enable the use of generic relations in forms |
| 571 |
and the admin. See the :doc:`model formset </topics/forms/modelforms>` and |
| 572 |
:ref:`admin <using-generic-relations-as-an-inline>` documentation for more |
| 573 |
information. |
| 574 |
|
| 575 |
.. class:: GenericInlineModelAdmin |
| 576 |
|
| 577 |
The :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin` |
| 578 |
class inherits all properties from an |
| 579 |
:class:`~django.contrib.admin.InlineModelAdmin` class. However, |
| 580 |
it adds a couple of its own for working with the generic relation: |
| 581 |
|
| 582 |
.. attribute:: ct_field |
| 583 |
|
| 584 |
The name of the |
| 585 |
:class:`~django.contrib.contenttypes.models.ContentType` foreign key |
| 586 |
field on the model. Defaults to ``content_type``. |
| 587 |
|
| 588 |
.. attribute:: ct_fk_field |
| 589 |
|
| 590 |
The name of the integer field that represents the ID of the related |
| 591 |
object. Defaults to ``object_id``. |
| 592 |
|
| 593 |
.. class:: GenericTabularInline |
| 594 |
.. class:: GenericStackedInline |
| 595 |
|
| 596 |
Subclasses of :class:`GenericInlineModelAdmin` with stacked and tabular |
| 597 |
layouts, respectively. |
| 598 |
|
| 599 |
.. module:: django.contrib.contenttypes.prefetch |
| 600 |
|
| 601 |
``GenericPrefetch()`` |
| 602 |
--------------------- |
| 603 |
|
| 604 |
.. class:: GenericPrefetch(lookup, querysets, to_attr=None) |
| 605 |
|
| 606 |
This lookup is similar to ``Prefetch()`` and it should only be used on |
| 607 |
``GenericForeignKey``. The ``querysets`` argument accepts a list of querysets, |
| 608 |
each for a different ``ContentType``. This is useful for ``GenericForeignKey`` |
| 609 |
with non-homogeneous set of results. |
| 610 |
|
| 611 |
.. code-block:: pycon |
| 612 |
|
| 613 |
>>> from django.contrib.contenttypes.prefetch import GenericPrefetch |
| 614 |
>>> bookmark = Bookmark.objects.create(url="https://www.djangoproject.com/") |
| 615 |
>>> animal = Animal.objects.create(name="lion", weight=100) |
| 616 |
>>> TaggedItem.objects.create(tag="great", content_object=bookmark) |
| 617 |
>>> TaggedItem.objects.create(tag="awesome", content_object=animal) |
| 618 |
>>> prefetch = GenericPrefetch( |
| 619 |
... "content_object", [Bookmark.objects.all(), Animal.objects.only("name")] |
| 620 |
... ) |
| 621 |
>>> TaggedItem.objects.prefetch_related(prefetch).all() |
| 622 |
<QuerySet [<TaggedItem: Great>, <TaggedItem: Awesome>]> |