contenttypes.txt 25 KB

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