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(**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.
    
  116. 
    
  117. .. method:: ContentType.model_class()
    
  118. 
    
  119.     Returns the model class represented by this
    
  120.     :class:`~django.contrib.contenttypes.models.ContentType` instance.
    
  121. 
    
  122. For example, we could look up the
    
  123. :class:`~django.contrib.contenttypes.models.ContentType` for the
    
  124. :class:`~django.contrib.auth.models.User` model::
    
  125. 
    
  126.     >>> from django.contrib.contenttypes.models import ContentType
    
  127.     >>> user_type = ContentType.objects.get(app_label='auth', model='user')
    
  128.     >>> user_type
    
  129.     <ContentType: user>
    
  130. 
    
  131. And then use it to query for a particular
    
  132. :class:`~django.contrib.auth.models.User`, or to get access
    
  133. to the ``User`` model class::
    
  134. 
    
  135.     >>> user_type.model_class()
    
  136.     <class 'django.contrib.auth.models.User'>
    
  137.     >>> user_type.get_object_for_this_type(username='Guido')
    
  138.     <User: Guido>
    
  139. 
    
  140. Together,
    
  141. :meth:`~django.contrib.contenttypes.models.ContentType.get_object_for_this_type`
    
  142. and :meth:`~django.contrib.contenttypes.models.ContentType.model_class` enable
    
  143. two extremely important use cases:
    
  144. 
    
  145. 1. Using these methods, you can write high-level generic code that
    
  146.    performs queries on any installed model -- instead of importing and
    
  147.    using a single specific model class, you can pass an ``app_label`` and
    
  148.    ``model`` into a
    
  149.    :class:`~django.contrib.contenttypes.models.ContentType` lookup at
    
  150.    runtime, and then work with the model class or retrieve objects from it.
    
  151. 
    
  152. 2. You can relate another model to
    
  153.    :class:`~django.contrib.contenttypes.models.ContentType` as a way of
    
  154.    tying instances of it to particular model classes, and use these methods
    
  155.    to get access to those model classes.
    
  156. 
    
  157. Several of Django's bundled applications make use of the latter technique.
    
  158. For example,
    
  159. :class:`the permissions system <django.contrib.auth.models.Permission>` in
    
  160. Django's authentication framework uses a
    
  161. :class:`~django.contrib.auth.models.Permission` model with a foreign
    
  162. key to :class:`~django.contrib.contenttypes.models.ContentType`; this lets
    
  163. :class:`~django.contrib.auth.models.Permission` represent concepts like
    
  164. "can add blog entry" or "can delete news story".
    
  165. 
    
  166. The ``ContentTypeManager``
    
  167. --------------------------
    
  168. 
    
  169. .. class:: ContentTypeManager
    
  170. 
    
  171.     :class:`~django.contrib.contenttypes.models.ContentType` also has a custom
    
  172.     manager, :class:`~django.contrib.contenttypes.models.ContentTypeManager`,
    
  173.     which adds the following methods:
    
  174. 
    
  175.     .. method:: clear_cache()
    
  176. 
    
  177.         Clears an internal cache used by
    
  178.         :class:`~django.contrib.contenttypes.models.ContentType` to keep track
    
  179.         of models for which it has created
    
  180.         :class:`~django.contrib.contenttypes.models.ContentType` instances. You
    
  181.         probably won't ever need to call this method yourself; Django will call
    
  182.         it automatically when it's needed.
    
  183. 
    
  184.     .. method:: get_for_id(id)
    
  185. 
    
  186.         Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by ID.
    
  187.         Since this method uses the same shared cache as
    
  188.         :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`,
    
  189.         it's preferred to use this method over the usual
    
  190.         ``ContentType.objects.get(pk=id)``
    
  191. 
    
  192.     .. method:: get_for_model(model, for_concrete_model=True)
    
  193. 
    
  194.         Takes either a model class or an instance of a model, and returns the
    
  195.         :class:`~django.contrib.contenttypes.models.ContentType` instance
    
  196.         representing that model. ``for_concrete_model=False`` allows fetching
    
  197.         the :class:`~django.contrib.contenttypes.models.ContentType` of a proxy
    
  198.         model.
    
  199. 
    
  200.     .. method:: get_for_models(*models, for_concrete_models=True)
    
  201. 
    
  202.         Takes a variadic number of model classes, and returns a dictionary
    
  203.         mapping the model classes to the
    
  204.         :class:`~django.contrib.contenttypes.models.ContentType` instances
    
  205.         representing them. ``for_concrete_models=False`` allows fetching the
    
  206.         :class:`~django.contrib.contenttypes.models.ContentType` of proxy
    
  207.         models.
    
  208. 
    
  209.     .. method:: get_by_natural_key(app_label, model)
    
  210. 
    
  211.         Returns the :class:`~django.contrib.contenttypes.models.ContentType`
    
  212.         instance uniquely identified by the given application label and model
    
  213.         name. The primary purpose of this method is to allow
    
  214.         :class:`~django.contrib.contenttypes.models.ContentType` objects to be
    
  215.         referenced via a :ref:`natural key<topics-serialization-natural-keys>`
    
  216.         during deserialization.
    
  217. 
    
  218. The :meth:`~ContentTypeManager.get_for_model()` method is especially
    
  219. useful when you know you need to work with a
    
  220. :class:`ContentType <django.contrib.contenttypes.models.ContentType>` but don't
    
  221. want to go to the trouble of obtaining the model's metadata to perform a manual
    
  222. lookup::
    
  223. 
    
  224.     >>> from django.contrib.auth.models import User
    
  225.     >>> ContentType.objects.get_for_model(User)
    
  226.     <ContentType: user>
    
  227. 
    
  228. .. module:: django.contrib.contenttypes.fields
    
  229. 
    
  230. .. _generic-relations:
    
  231. 
    
  232. Generic relations
    
  233. =================
    
  234. 
    
  235. Adding a foreign key from one of your own models to
    
  236. :class:`~django.contrib.contenttypes.models.ContentType` allows your model to
    
  237. effectively tie itself to another model class, as in the example of the
    
  238. :class:`~django.contrib.auth.models.Permission` model above. But it's possible
    
  239. to go one step further and use
    
  240. :class:`~django.contrib.contenttypes.models.ContentType` to enable truly
    
  241. generic (sometimes called "polymorphic") relationships between models.
    
  242. 
    
  243. For example, it could be used for a tagging system like so::
    
  244. 
    
  245.     from django.contrib.contenttypes.fields import GenericForeignKey
    
  246.     from django.contrib.contenttypes.models import ContentType
    
  247.     from django.db import models
    
  248. 
    
  249.     class TaggedItem(models.Model):
    
  250.         tag = models.SlugField()
    
  251.         content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    
  252.         object_id = models.PositiveIntegerField()
    
  253.         content_object = GenericForeignKey('content_type', 'object_id')
    
  254. 
    
  255.         def __str__(self):
    
  256.             return self.tag
    
  257. 
    
  258.         class Meta:
    
  259.             indexes = [
    
  260.                 models.Index(fields=["content_type", "object_id"]),
    
  261.             ]
    
  262. 
    
  263. A normal :class:`~django.db.models.ForeignKey` can only "point
    
  264. to" one other model, which means that if the ``TaggedItem`` model used a
    
  265. :class:`~django.db.models.ForeignKey` it would have to
    
  266. choose one and only one model to store tags for. The contenttypes
    
  267. application provides a special field type (``GenericForeignKey``) which
    
  268. works around this and allows the relationship to be with any
    
  269. model:
    
  270. 
    
  271. .. class:: GenericForeignKey
    
  272. 
    
  273.     There are three parts to setting up a
    
  274.     :class:`~django.contrib.contenttypes.fields.GenericForeignKey`:
    
  275. 
    
  276.     1. Give your model a :class:`~django.db.models.ForeignKey`
    
  277.        to :class:`~django.contrib.contenttypes.models.ContentType`. The usual
    
  278.        name for this field is "content_type".
    
  279. 
    
  280.     2. Give your model a field that can store primary key values from the
    
  281.        models you'll be relating to. For most models, this means a
    
  282.        :class:`~django.db.models.PositiveIntegerField`. The usual name
    
  283.        for this field is "object_id".
    
  284. 
    
  285.     3. Give your model a
    
  286.        :class:`~django.contrib.contenttypes.fields.GenericForeignKey`, and
    
  287.        pass it the names of the two fields described above. If these fields
    
  288.        are named "content_type" and "object_id", you can omit this -- those
    
  289.        are the default field names
    
  290.        :class:`~django.contrib.contenttypes.fields.GenericForeignKey` will
    
  291.        look for.
    
  292. 
    
  293.     Unlike for the :class:`~django.db.models.ForeignKey`, a database index is
    
  294.     *not* automatically created on the
    
  295.     :class:`~django.contrib.contenttypes.fields.GenericForeignKey`, so it's
    
  296.     recommended that you use
    
  297.     :attr:`Meta.indexes <django.db.models.Options.indexes>` to add your own
    
  298.     multiple column index. This behavior :ticket:`may change <23435>` in the
    
  299.     future.
    
  300. 
    
  301.     .. attribute:: GenericForeignKey.for_concrete_model
    
  302. 
    
  303.        If ``False``, the field will be able to reference proxy models. Default
    
  304.        is ``True``. This mirrors the ``for_concrete_model`` argument to
    
  305.        :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`.
    
  306. 
    
  307. .. admonition:: Primary key type compatibility
    
  308. 
    
  309.    The "object_id" field doesn't have to be the same type as the
    
  310.    primary key fields on the related models, but their primary key values
    
  311.    must be coercible to the same type as the "object_id" field by its
    
  312.    :meth:`~django.db.models.Field.get_db_prep_value` method.
    
  313. 
    
  314.    For example, if you want to allow generic relations to models with either
    
  315.    :class:`~django.db.models.IntegerField` or
    
  316.    :class:`~django.db.models.CharField` primary key fields, you
    
  317.    can use :class:`~django.db.models.CharField` for the
    
  318.    "object_id" field on your model since integers can be coerced to
    
  319.    strings by :meth:`~django.db.models.Field.get_db_prep_value`.
    
  320. 
    
  321.    For maximum flexibility you can use a
    
  322.    :class:`~django.db.models.TextField` which doesn't have a
    
  323.    maximum length defined, however this may incur significant performance
    
  324.    penalties depending on your database backend.
    
  325. 
    
  326.    There is no one-size-fits-all solution for which field type is best. You
    
  327.    should evaluate the models you expect to be pointing to and determine
    
  328.    which solution will be most effective for your use case.
    
  329. 
    
  330. .. admonition:: Serializing references to ``ContentType`` objects
    
  331. 
    
  332.    If you're serializing data (for example, when generating
    
  333.    :class:`~django.test.TransactionTestCase.fixtures`) from a model that implements
    
  334.    generic relations, you should probably be using a natural key to uniquely
    
  335.    identify related :class:`~django.contrib.contenttypes.models.ContentType`
    
  336.    objects. See :ref:`natural keys<topics-serialization-natural-keys>` and
    
  337.    :option:`dumpdata --natural-foreign` for more information.
    
  338. 
    
  339. This will enable an API similar to the one used for a normal
    
  340. :class:`~django.db.models.ForeignKey`;
    
  341. each ``TaggedItem`` will have a ``content_object`` field that returns the
    
  342. object it's related to, and you can also assign to that field or use it when
    
  343. creating a ``TaggedItem``::
    
  344. 
    
  345.     >>> from django.contrib.auth.models import User
    
  346.     >>> guido = User.objects.get(username='Guido')
    
  347.     >>> t = TaggedItem(content_object=guido, tag='bdfl')
    
  348.     >>> t.save()
    
  349.     >>> t.content_object
    
  350.     <User: Guido>
    
  351. 
    
  352. If the related object is deleted, the ``content_type`` and ``object_id`` fields
    
  353. remain set to their original values and the ``GenericForeignKey`` returns
    
  354. ``None``::
    
  355. 
    
  356.     >>> guido.delete()
    
  357.     >>> t.content_object  # returns None
    
  358. 
    
  359. Due to the way :class:`~django.contrib.contenttypes.fields.GenericForeignKey`
    
  360. is implemented, you cannot use such fields directly with filters (``filter()``
    
  361. and ``exclude()``, for example) via the database API. Because a
    
  362. :class:`~django.contrib.contenttypes.fields.GenericForeignKey` isn't a
    
  363. normal field object, these examples will *not* work::
    
  364. 
    
  365.     # This will fail
    
  366.     >>> TaggedItem.objects.filter(content_object=guido)
    
  367.     # This will also fail
    
  368.     >>> TaggedItem.objects.get(content_object=guido)
    
  369. 
    
  370. Likewise, :class:`~django.contrib.contenttypes.fields.GenericForeignKey`\s
    
  371. does not appear in :class:`~django.forms.ModelForm`\s.
    
  372. 
    
  373. Reverse generic relations
    
  374. -------------------------
    
  375. 
    
  376. .. class:: GenericRelation
    
  377. 
    
  378.     .. attribute:: related_query_name
    
  379. 
    
  380.         The relation on the related object back to this object doesn't exist by
    
  381.         default. Setting ``related_query_name`` creates a relation from the
    
  382.         related object back to this one. This allows querying and filtering
    
  383.         from the related object.
    
  384. 
    
  385. If you know which models you'll be using most often, you can also add
    
  386. a "reverse" generic relationship to enable an additional API. For example::
    
  387. 
    
  388.     from django.contrib.contenttypes.fields import GenericRelation
    
  389.     from django.db import models
    
  390. 
    
  391.     class Bookmark(models.Model):
    
  392.         url = models.URLField()
    
  393.         tags = GenericRelation(TaggedItem)
    
  394. 
    
  395. ``Bookmark`` instances will each have a ``tags`` attribute, which can
    
  396. be used to retrieve their associated ``TaggedItems``::
    
  397. 
    
  398.     >>> b = Bookmark(url='https://www.djangoproject.com/')
    
  399.     >>> b.save()
    
  400.     >>> t1 = TaggedItem(content_object=b, tag='django')
    
  401.     >>> t1.save()
    
  402.     >>> t2 = TaggedItem(content_object=b, tag='python')
    
  403.     >>> t2.save()
    
  404.     >>> b.tags.all()
    
  405.     <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
    
  406. 
    
  407. You can also use ``add()``, ``create()``, or ``set()`` to create
    
  408. relationships::
    
  409. 
    
  410.     >>> t3 = TaggedItem(tag='Web development')
    
  411.     >>> b.tags.add(t3, bulk=False)
    
  412.     >>> b.tags.create(tag='Web framework')
    
  413.     <TaggedItem: Web framework>
    
  414.     >>> b.tags.all()
    
  415.     <QuerySet [<TaggedItem: django>, <TaggedItem: python>, <TaggedItem: Web development>, <TaggedItem: Web framework>]>
    
  416.     >>> b.tags.set([t1, t3])
    
  417.     >>> b.tags.all()
    
  418.     <QuerySet [<TaggedItem: django>, <TaggedItem: Web development>]>
    
  419. 
    
  420. The ``remove()`` call will bulk delete the specified model objects::
    
  421. 
    
  422.     >>> b.tags.remove(t3)
    
  423.     >>> b.tags.all()
    
  424.     <QuerySet [<TaggedItem: django>]>
    
  425.     >>> TaggedItem.objects.all()
    
  426.     <QuerySet [<TaggedItem: django>]>
    
  427. 
    
  428. The ``clear()`` method can be used to bulk delete all related objects for an
    
  429. instance::
    
  430. 
    
  431.     >>> b.tags.clear()
    
  432.     >>> b.tags.all()
    
  433.     <QuerySet []>
    
  434.     >>> TaggedItem.objects.all()
    
  435.     <QuerySet []>
    
  436. 
    
  437. Defining :class:`~django.contrib.contenttypes.fields.GenericRelation` with
    
  438. ``related_query_name`` set allows querying from the related object::
    
  439. 
    
  440.     tags = GenericRelation(TaggedItem, related_query_name='bookmark')
    
  441. 
    
  442. This enables filtering, ordering, and other query operations on ``Bookmark``
    
  443. from ``TaggedItem``::
    
  444. 
    
  445.     >>> # Get all tags belonging to bookmarks containing `django` in the url
    
  446.     >>> TaggedItem.objects.filter(bookmark__url__contains='django')
    
  447.     <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
    
  448. 
    
  449. If you don't add the ``related_query_name``, you can do the same types of
    
  450. lookups manually::
    
  451. 
    
  452.     >>> bookmarks = Bookmark.objects.filter(url__contains='django')
    
  453.     >>> bookmark_type = ContentType.objects.get_for_model(Bookmark)
    
  454.     >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id, object_id__in=bookmarks)
    
  455.     <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
    
  456. 
    
  457. Just as :class:`~django.contrib.contenttypes.fields.GenericForeignKey`
    
  458. accepts the names of the content-type and object-ID fields as
    
  459. arguments, so too does
    
  460. :class:`~django.contrib.contenttypes.fields.GenericRelation`;
    
  461. if the model which has the generic foreign key is using non-default names
    
  462. for those fields, you must pass the names of the fields when setting up a
    
  463. :class:`.GenericRelation` to it. For example, if the ``TaggedItem`` model
    
  464. referred to above used fields named ``content_type_fk`` and
    
  465. ``object_primary_key`` to create its generic foreign key, then a
    
  466. :class:`.GenericRelation` back to it would need to be defined like so::
    
  467. 
    
  468.     tags = GenericRelation(
    
  469.         TaggedItem,
    
  470.         content_type_field='content_type_fk',
    
  471.         object_id_field='object_primary_key',
    
  472.     )
    
  473. 
    
  474. Note also, that if you delete an object that has a
    
  475. :class:`~django.contrib.contenttypes.fields.GenericRelation`, any objects
    
  476. which have a :class:`~django.contrib.contenttypes.fields.GenericForeignKey`
    
  477. pointing at it will be deleted as well. In the example above, this means that
    
  478. if a ``Bookmark`` object were deleted, any ``TaggedItem`` objects pointing at
    
  479. it would be deleted at the same time.
    
  480. 
    
  481. Unlike :class:`~django.db.models.ForeignKey`,
    
  482. :class:`~django.contrib.contenttypes.fields.GenericForeignKey` does not accept
    
  483. an :attr:`~django.db.models.ForeignKey.on_delete` argument to customize this
    
  484. behavior; if desired, you can avoid the cascade-deletion by not using
    
  485. :class:`~django.contrib.contenttypes.fields.GenericRelation`, and alternate
    
  486. behavior can be provided via the :data:`~django.db.models.signals.pre_delete`
    
  487. signal.
    
  488. 
    
  489. Generic relations and aggregation
    
  490. ---------------------------------
    
  491. 
    
  492. :doc:`Django's database aggregation API </topics/db/aggregation>` works with a
    
  493. :class:`~django.contrib.contenttypes.fields.GenericRelation`. For example, you
    
  494. can find out how many tags all the bookmarks have::
    
  495. 
    
  496.     >>> Bookmark.objects.aggregate(Count('tags'))
    
  497.     {'tags__count': 3}
    
  498. 
    
  499. .. module:: django.contrib.contenttypes.forms
    
  500. 
    
  501. Generic relation in forms
    
  502. -------------------------
    
  503. 
    
  504. The :mod:`django.contrib.contenttypes.forms` module provides:
    
  505. 
    
  506. * :class:`BaseGenericInlineFormSet`
    
  507. * A formset factory, :func:`generic_inlineformset_factory`, for use with
    
  508.   :class:`~django.contrib.contenttypes.fields.GenericForeignKey`.
    
  509. 
    
  510. .. class:: BaseGenericInlineFormSet
    
  511. 
    
  512. .. 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)
    
  513. 
    
  514.     Returns a ``GenericInlineFormSet`` using
    
  515.     :func:`~django.forms.models.modelformset_factory`.
    
  516. 
    
  517.     You must provide ``ct_field`` and ``fk_field`` if they are different from
    
  518.     the defaults, ``content_type`` and ``object_id`` respectively. Other
    
  519.     parameters are similar to those documented in
    
  520.     :func:`~django.forms.models.modelformset_factory` and
    
  521.     :func:`~django.forms.models.inlineformset_factory`.
    
  522. 
    
  523.     The ``for_concrete_model`` argument corresponds to the
    
  524.     :class:`~django.contrib.contenttypes.fields.GenericForeignKey.for_concrete_model`
    
  525.     argument on ``GenericForeignKey``.
    
  526. 
    
  527. .. module:: django.contrib.contenttypes.admin
    
  528. 
    
  529. Generic relations in admin
    
  530. --------------------------
    
  531. 
    
  532. The :mod:`django.contrib.contenttypes.admin` module provides
    
  533. :class:`~django.contrib.contenttypes.admin.GenericTabularInline` and
    
  534. :class:`~django.contrib.contenttypes.admin.GenericStackedInline` (subclasses of
    
  535. :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)
    
  536. 
    
  537. These classes and functions enable the use of generic relations in forms
    
  538. and the admin. See the :doc:`model formset </topics/forms/modelforms>` and
    
  539. :ref:`admin <using-generic-relations-as-an-inline>` documentation for more
    
  540. information.
    
  541. 
    
  542. .. class:: GenericInlineModelAdmin
    
  543. 
    
  544.     The :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`
    
  545.     class inherits all properties from an
    
  546.     :class:`~django.contrib.admin.InlineModelAdmin` class. However,
    
  547.     it adds a couple of its own for working with the generic relation:
    
  548. 
    
  549.     .. attribute:: ct_field
    
  550. 
    
  551.         The name of the
    
  552.         :class:`~django.contrib.contenttypes.models.ContentType` foreign key
    
  553.         field on the model. Defaults to ``content_type``.
    
  554. 
    
  555.     .. attribute:: ct_fk_field
    
  556. 
    
  557.         The name of the integer field that represents the ID of the related
    
  558.         object. Defaults to ``object_id``.
    
  559. 
    
  560. .. class:: GenericTabularInline
    
  561. .. class:: GenericStackedInline
    
  562. 
    
  563.     Subclasses of :class:`GenericInlineModelAdmin` with stacked and tabular
    
  564.     layouts, respectively.