contenttypes.txt 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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.py 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. * Django's comments system (:mod:`django.contrib.comments`) uses it to
  43. "attach" comments to any installed model.
  44. .. currentmodule:: django.contrib.contenttypes.models
  45. The ``ContentType`` model
  46. =========================
  47. .. class:: ContentType
  48. Each instance of :class:`~django.contrib.contenttypes.models.ContentType`
  49. has three fields which, taken together, uniquely describe an installed
  50. model:
  51. .. attribute:: app_label
  52. The name of the application the model is part of. This is taken from
  53. the :attr:`app_label` attribute of the model, and includes only the
  54. *last* part of the application's Python import path;
  55. "django.contrib.contenttypes", for example, becomes an
  56. :attr:`app_label` of "contenttypes".
  57. .. attribute:: model
  58. The name of the model class.
  59. .. attribute:: name
  60. The human-readable name of the model. This is taken from the
  61. :attr:`verbose_name <django.db.models.Field.verbose_name>`
  62. attribute of the model.
  63. Let's look at an example to see how this works. If you already have
  64. the :mod:`~django.contrib.contenttypes` application installed, and then add
  65. :mod:`the sites application <django.contrib.sites>` to your
  66. :setting:`INSTALLED_APPS` setting and run ``manage.py syncdb`` to install it,
  67. the model :class:`django.contrib.sites.models.Site` will be installed into
  68. your database. Along with it a new instance of
  69. :class:`~django.contrib.contenttypes.models.ContentType` will be
  70. created with the following values:
  71. * :attr:`~django.contrib.contenttypes.models.ContentType.app_label`
  72. will be set to ``'sites'`` (the last part of the Python
  73. path "django.contrib.sites").
  74. * :attr:`~django.contrib.contenttypes.models.ContentType.model`
  75. will be set to ``'site'``.
  76. * :attr:`~django.contrib.contenttypes.models.ContentType.name`
  77. will be set to ``'site'``.
  78. .. _the verbose_name attribute: ../model-api/#verbose_name
  79. Methods on ``ContentType`` instances
  80. ====================================
  81. Each :class:`~django.contrib.contenttypes.models.ContentType` instance has
  82. methods that allow you to get from a
  83. :class:`~django.contrib.contenttypes.models.ContentType` instance to the
  84. model it represents, or to retrieve objects from that model:
  85. .. method:: ContentType.get_object_for_this_type(**kwargs)
  86. Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the
  87. model the :class:`~django.contrib.contenttypes.models.ContentType`
  88. represents, and does
  89. :meth:`a get() lookup <django.db.models.query.QuerySet.get>`
  90. on that model, returning the corresponding object.
  91. .. method:: ContentType.model_class()
  92. Returns the model class represented by this
  93. :class:`~django.contrib.contenttypes.models.ContentType` instance.
  94. For example, we could look up the
  95. :class:`~django.contrib.contenttypes.models.ContentType` for the
  96. :class:`~django.contrib.auth.models.User` model::
  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. >>> user_type.model_class()
  105. <class 'django.contrib.auth.models.User'>
  106. >>> user_type.get_object_for_this_type(username='Guido')
  107. <User: Guido>
  108. Together,
  109. :meth:`~django.contrib.contenttypes.models.ContentType.get_object_for_this_type`
  110. and :meth:`~django.contrib.contenttypes.models.ContentType.model_class` enable
  111. two extremely important use cases:
  112. 1. Using these methods, you can write high-level generic code that
  113. performs queries on any installed model -- instead of importing and
  114. using a single specific model class, you can pass an ``app_label`` and
  115. ``model`` into a
  116. :class:`~django.contrib.contenttypes.models.ContentType` lookup at
  117. runtime, and then work with the model class or retrieve objects from it.
  118. 2. You can relate another model to
  119. :class:`~django.contrib.contenttypes.models.ContentType` as a way of
  120. tying instances of it to particular model classes, and use these methods
  121. to get access to those model classes.
  122. Several of Django's bundled applications make use of the latter technique.
  123. For example,
  124. :class:`the permissions system <django.contrib.auth.models.Permission>` in
  125. Django's authentication framework uses a
  126. :class:`~django.contrib.auth.models.Permission` model with a foreign
  127. key to :class:`~django.contrib.contenttypes.models.ContentType`; this lets
  128. :class:`~django.contrib.auth.models.Permission` represent concepts like
  129. "can add blog entry" or "can delete news story".
  130. The ``ContentTypeManager``
  131. --------------------------
  132. .. class:: ContentTypeManager
  133. :class:`~django.contrib.contenttypes.models.ContentType` also has a custom
  134. manager, :class:`~django.contrib.contenttypes.models.ContentTypeManager`,
  135. which adds the following methods:
  136. .. method:: clear_cache()
  137. Clears an internal cache used by
  138. :class:`~django.contrib.contenttypes.models.ContentType` to keep track
  139. of which models for which it has created
  140. :class:`~django.contrib.contenttypes.models.ContentType` instances. You
  141. probably won't ever need to call this method yourself; Django will call
  142. it automatically when it's needed.
  143. .. method:: get_for_id(id)
  144. Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by ID.
  145. Since this method uses the same shared cache as
  146. :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`,
  147. it's preferred to use this method over the usual
  148. ``ContentType.objects.get(pk=id)``
  149. .. method:: get_for_model(model[, for_concrete_model=True])
  150. Takes either a model class or an instance of a model, and returns the
  151. :class:`~django.contrib.contenttypes.models.ContentType` instance
  152. representing that model.
  153. .. method:: get_for_models(*models[, for_concrete_models=True])
  154. Takes a variadic number of model classes, and returns a dictionary
  155. mapping the model classes to the
  156. :class:`~django.contrib.contenttypes.models.ContentType` instances
  157. representing them.
  158. .. method:: get_by_natural_key(app_label, model)
  159. Returns the :class:`~django.contrib.contenttypes.models.ContentType`
  160. instance uniquely identified by the given application label and model
  161. name. The primary purpose of this method is to allow
  162. :class:`~django.contrib.contenttypes.models.ContentType` objects to be
  163. referenced via a :ref:`natural key<topics-serialization-natural-keys>`
  164. during deserialization.
  165. The :meth:`~ContentTypeManager.get_for_model()` method is especially
  166. useful when you know you need to work with a
  167. :class:`ContentType <django.contrib.contenttypes.models.ContentType>` but don't
  168. want to go to the trouble of obtaining the model's metadata to perform a manual
  169. lookup::
  170. >>> from django.contrib.auth.models import User
  171. >>> user_type = ContentType.objects.get_for_model(User)
  172. >>> user_type
  173. <ContentType: user>
  174. .. module:: django.contrib.contenttypes.generic
  175. .. _generic-relations:
  176. .. versionadded:: 1.5
  177. Prior to Django 1.5 :meth:`~ContentTypeManager.get_for_model()` and
  178. :meth:`~ContentTypeManager.get_for_models()` always returned the
  179. :class:`~django.contrib.contenttypes.models.ContentType` associated with the
  180. concrete model of the specified one(s). That means there was no way to retreive
  181. the :class:`~django.contrib.contenttypes.models.ContentType` of a proxy model
  182. using those methods. As of Django 1.5 you can now pass a boolean flag –
  183. respectively ``for_concrete_model`` and ``for_concrete_models`` – to specify
  184. wether or not you want to retreive the
  185. :class:`~django.contrib.contenttypes.models.ContentType` for the concrete or
  186. direct model.
  187. Generic relations
  188. =================
  189. Adding a foreign key from one of your own models to
  190. :class:`~django.contrib.contenttypes.models.ContentType` allows your model to
  191. effectively tie itself to another model class, as in the example of the
  192. :class:`~django.contrib.auth.models.Permission` model above. But it's possible
  193. to go one step further and use
  194. :class:`~django.contrib.contenttypes.models.ContentType` to enable truly
  195. generic (sometimes called "polymorphic") relationships between models.
  196. A simple example is a tagging system, which might look like this::
  197. from django.db import models
  198. from django.contrib.contenttypes.models import ContentType
  199. from django.contrib.contenttypes import generic
  200. class TaggedItem(models.Model):
  201. tag = models.SlugField()
  202. content_type = models.ForeignKey(ContentType)
  203. object_id = models.PositiveIntegerField()
  204. content_object = generic.GenericForeignKey('content_type', 'object_id')
  205. def __unicode__(self):
  206. return self.tag
  207. A normal :class:`~django.db.models.ForeignKey` can only "point
  208. to" one other model, which means that if the ``TaggedItem`` model used a
  209. :class:`~django.db.models.ForeignKey` it would have to
  210. choose one and only one model to store tags for. The contenttypes
  211. application provides a special field type which
  212. works around this and allows the relationship to be with any
  213. model:
  214. .. class:: GenericForeignKey
  215. There are three parts to setting up a
  216. :class:`~django.contrib.contenttypes.generic.GenericForeignKey`:
  217. 1. Give your model a :class:`~django.db.models.ForeignKey`
  218. to :class:`~django.contrib.contenttypes.models.ContentType`.
  219. 2. Give your model a field that can store primary key values from the
  220. models you'll be relating to. For most models, this means a
  221. :class:`~django.db.models.PositiveIntegerField`. The usual name
  222. for this field is "object_id".
  223. 3. Give your model a
  224. :class:`~django.contrib.contenttypes.generic.GenericForeignKey`, and
  225. pass it the names of the two fields described above. If these fields
  226. are named "content_type" and "object_id", you can omit this -- those
  227. are the default field names
  228. :class:`~django.contrib.contenttypes.generic.GenericForeignKey` will
  229. look for.
  230. .. admonition:: Primary key type compatibility
  231. The "object_id" field doesn't have to be the same type as the
  232. primary key fields on the related models, but their primary key values
  233. must be coercible to the same type as the "object_id" field by its
  234. :meth:`~django.db.models.Field.get_db_prep_value` method.
  235. For example, if you want to allow generic relations to models with either
  236. :class:`~django.db.models.IntegerField` or
  237. :class:`~django.db.models.CharField` primary key fields, you
  238. can use :class:`~django.db.models.CharField` for the
  239. "object_id" field on your model since integers can be coerced to
  240. strings by :meth:`~django.db.models.Field.get_db_prep_value`.
  241. For maximum flexibility you can use a
  242. :class:`~django.db.models.TextField` which doesn't have a
  243. maximum length defined, however this may incur significant performance
  244. penalties depending on your database backend.
  245. There is no one-size-fits-all solution for which field type is best. You
  246. should evaluate the models you expect to be pointing to and determine
  247. which solution will be most effective for your use case.
  248. .. admonition:: Serializing references to ``ContentType`` objects
  249. If you're serializing data (for example, when generating
  250. :class:`~django.test.TestCase.fixtures`) from a model that implements
  251. generic relations, you should probably be using a natural key to uniquely
  252. identify related :class:`~django.contrib.contenttypes.models.ContentType`
  253. objects. See :ref:`natural keys<topics-serialization-natural-keys>` and
  254. :djadminopt:`dumpdata --natural <--natural>` for more information.
  255. This will enable an API similar to the one used for a normal
  256. :class:`~django.db.models.ForeignKey`;
  257. each ``TaggedItem`` will have a ``content_object`` field that returns the
  258. object it's related to, and you can also assign to that field or use it when
  259. creating a ``TaggedItem``::
  260. >>> from django.contrib.auth.models import User
  261. >>> guido = User.objects.get(username='Guido')
  262. >>> t = TaggedItem(content_object=guido, tag='bdfl')
  263. >>> t.save()
  264. >>> t.content_object
  265. <User: Guido>
  266. Due to the way :class:`~django.contrib.contenttypes.generic.GenericForeignKey`
  267. is implemented, you cannot use such fields directly with filters (``filter()``
  268. and ``exclude()``, for example) via the database API. Because a
  269. :class:`~django.contrib.contenttypes.generic.GenericForeignKey` isn't a
  270. normal field object, these examples will *not* work::
  271. # This will fail
  272. >>> TaggedItem.objects.filter(content_object=guido)
  273. # This will also fail
  274. >>> TaggedItem.objects.get(content_object=guido)
  275. Reverse generic relations
  276. -------------------------
  277. .. class:: GenericRelation
  278. If you know which models you'll be using most often, you can also add
  279. a "reverse" generic relationship to enable an additional API. For example::
  280. class Bookmark(models.Model):
  281. url = models.URLField()
  282. tags = generic.GenericRelation(TaggedItem)
  283. ``Bookmark`` instances will each have a ``tags`` attribute, which can
  284. be used to retrieve their associated ``TaggedItems``::
  285. >>> b = Bookmark(url='https://www.djangoproject.com/')
  286. >>> b.save()
  287. >>> t1 = TaggedItem(content_object=b, tag='django')
  288. >>> t1.save()
  289. >>> t2 = TaggedItem(content_object=b, tag='python')
  290. >>> t2.save()
  291. >>> b.tags.all()
  292. [<TaggedItem: django>, <TaggedItem: python>]
  293. Just as :class:`~django.contrib.contenttypes.generic.GenericForeignKey`
  294. accepts the names of the content-type and object-ID fields as
  295. arguments, so too does
  296. :class:`~django.contrib.contenttypes.generic.GenericRelation`;
  297. if the model which has the generic foreign key is using non-default names
  298. for those fields, you must pass the names of the fields when setting up a
  299. :class:`.GenericRelation` to it. For example, if the ``TaggedItem`` model
  300. referred to above used fields named ``content_type_fk`` and
  301. ``object_primary_key`` to create its generic foreign key, then a
  302. :class:`.GenericRelation` back to it would need to be defined like so::
  303. tags = generic.GenericRelation(TaggedItem,
  304. content_type_field='content_type_fk',
  305. object_id_field='object_primary_key')
  306. Of course, if you don't add the reverse relationship, you can do the
  307. same types of lookups manually::
  308. >>> b = Bookmark.objects.get(url='https://www.djangoproject.com/')
  309. >>> bookmark_type = ContentType.objects.get_for_model(b)
  310. >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id,
  311. ... object_id=b.id)
  312. [<TaggedItem: django>, <TaggedItem: python>]
  313. Note that if the model in a
  314. :class:`~django.contrib.contenttypes.generic.GenericRelation` uses a
  315. non-default value for ``ct_field`` or ``fk_field`` in its
  316. :class:`~django.contrib.contenttypes.generic.GenericForeignKey` (e.g. the
  317. :mod:`django.contrib.comments` app uses ``ct_field="object_pk"``),
  318. you'll need to set ``content_type_field`` and/or ``object_id_field`` in
  319. the :class:`~django.contrib.contenttypes.generic.GenericRelation` to
  320. match the ``ct_field`` and ``fk_field``, respectively, in the
  321. :class:`~django.contrib.contenttypes.generic.GenericForeignKey`::
  322. comments = generic.GenericRelation(Comment, object_id_field="object_pk")
  323. Note also, that if you delete an object that has a
  324. :class:`~django.contrib.contenttypes.generic.GenericRelation`, any objects
  325. which have a :class:`~django.contrib.contenttypes.generic.GenericForeignKey`
  326. pointing at it will be deleted as well. In the example above, this means that
  327. if a ``Bookmark`` object were deleted, any ``TaggedItem`` objects pointing at
  328. it would be deleted at the same time.
  329. Unlike :class:`~django.db.models.ForeignKey`,
  330. :class:`~django.contrib.contenttypes.generic.GenericForeignKey` does not accept
  331. an :attr:`~django.db.models.ForeignKey.on_delete` argument to customize this
  332. behavior; if desired, you can avoid the cascade-deletion simply by not using
  333. :class:`~django.contrib.contenttypes.generic.GenericRelation`, and alternate
  334. behavior can be provided via the :data:`~django.db.models.signals.pre_delete`
  335. signal.
  336. Generic relations and aggregation
  337. ---------------------------------
  338. :doc:`Django's database aggregation API </topics/db/aggregation>`
  339. doesn't work with a
  340. :class:`~django.contrib.contenttypes.generic.GenericRelation`. For example, you
  341. might be tempted to try something like::
  342. Bookmark.objects.aggregate(Count('tags'))
  343. This will not work correctly, however. The generic relation adds extra filters
  344. to the queryset to ensure the correct content type, but the
  345. :meth:`~django.db.models.query.QuerySet.aggregate` method doesn't take them
  346. into account. For now, if you need aggregates on generic relations, you'll
  347. need to calculate them without using the aggregation API.
  348. Generic relations in forms and admin
  349. ------------------------------------
  350. The :mod:`django.contrib.contenttypes.generic` module provides
  351. :class:`~django.contrib.contenttypes.generic.BaseGenericInlineFormSet`,
  352. :class:`~django.contrib.contenttypes.generic.GenericTabularInline`
  353. and :class:`~django.contrib.contenttypes.generic.GenericStackedInline`
  354. (the last two are subclasses of
  355. :class:`~django.contrib.contenttypes.generic.GenericInlineModelAdmin`).
  356. This enables the use of generic relations in forms and the admin. See the
  357. :doc:`model formset </topics/forms/modelforms>` and
  358. :ref:`admin <using-generic-relations-as-an-inline>` documentation for more
  359. information.
  360. .. class:: GenericInlineModelAdmin
  361. The :class:`~django.contrib.contenttypes.generic.GenericInlineModelAdmin`
  362. class inherits all properties from an
  363. :class:`~django.contrib.admin.InlineModelAdmin` class. However,
  364. it adds a couple of its own for working with the generic relation:
  365. .. attribute:: ct_field
  366. The name of the
  367. :class:`~django.contrib.contenttypes.models.ContentType` foreign key
  368. field on the model. Defaults to ``content_type``.
  369. .. attribute:: ct_fk_field
  370. The name of the integer field that represents the ID of the related
  371. object. Defaults to ``object_id``.