contenttypes.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. ==========================
  2. The contenttypes framework
  3. ==========================
  4. .. module:: django.contrib.contenttypes
  5. :synopsis: Provides generic interface to installed models.
  6. Django includes a :mod:`contenttypes` application that can track all of
  7. 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. The ``ContentType`` model
  45. =========================
  46. .. class:: models.ContentType
  47. Each instance of :class:`~django.contrib.contenttypes.models.ContentType`
  48. has three fields which, taken together, uniquely describe an installed model:
  49. .. attribute:: models.ContentType.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 *last*
  52. part of the application's Python import path;
  53. "django.contrib.contenttypes", for example, becomes an :attr:`app_label`
  54. of "contenttypes".
  55. .. attribute:: models.ContentType.model
  56. The name of the model class.
  57. .. attribute:: models.ContentType.name
  58. The human-readable name of the model. This is taken from the
  59. :attr:`verbose_name <django.db.models.fields.Field.verbose_name>`
  60. attribute of the model.
  61. Let's look at an example to see how this works. If you already have
  62. the contenttypes application installed, and then add
  63. :mod:`the sites application <django.contrib.sites>` to your
  64. :setting:`INSTALLED_APPS` setting and run ``manage.py syncdb`` to install it,
  65. the model :class:`django.contrib.sites.models.Site` will be installed into
  66. your database. Along with it a new instance of
  67. :class:`~django.contrib.contenttypes.models.ContentType` will be
  68. created with the following values:
  69. * :attr:`app_label` will be set to ``'sites'`` (the last part of the Python
  70. path "django.contrib.sites").
  71. * :attr:`model` will be set to ``'site'``.
  72. * :attr:`name` will be set to ``'site'``.
  73. .. _the verbose_name attribute: ../model-api/#verbose_name
  74. Methods on ``ContentType`` instances
  75. ====================================
  76. .. class:: models.ContentType
  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 model
  80. it represents, or to retrieve objects from that model:
  81. .. method:: models.ContentType.get_object_for_this_type(**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 :ref:`a get() lookup <get-kwargs>` on that model,
  85. returning the corresponding object.
  86. .. method:: models.ContentType.model_class()
  87. Returns the model class represented by this
  88. :class:`~django.contrib.contenttypes.models.ContentType` instance.
  89. For example, we could look up the
  90. :class:`~django.contrib.contenttypes.models.ContentType` for the
  91. :class:`~django.contrib.auth.models.User` model::
  92. >>> from django.contrib.contenttypes.models import ContentType
  93. >>> user_type = ContentType.objects.get(app_label="auth", model="user")
  94. >>> user_type
  95. <ContentType: user>
  96. And then use it to query for a particular ``User``, or to get access
  97. to the ``User`` model class::
  98. >>> user_type.model_class()
  99. <class 'django.contrib.auth.models.User'>
  100. >>> user_type.get_object_for_this_type(username='Guido')
  101. <User: Guido>
  102. Together,
  103. :meth:`~django.contrib.contenttypes.models.ContentType.get_object_for_this_type`
  104. and :meth:`~django.contrib.contenttypes.models.ContentType.model_class`
  105. enable two extremely important use cases:
  106. 1. Using these methods, you can write high-level generic code that
  107. performs queries on any installed model -- instead of importing and using
  108. a single specific model class, you can pass an ``app_label`` and
  109. ``model`` into a :class:`~django.contrib.contenttypes.models.ContentType`
  110. lookup at runtime, and then work with the model class or retrieve objects
  111. from it.
  112. 2. You can relate another model to
  113. :class:`~django.contrib.contenttypes.models.ContentType` as a way of
  114. tying instances of it to particular model classes, and use these methods
  115. to get access to those model classes.
  116. Several of Django's bundled applications make use of the latter technique.
  117. For example,
  118. :class:`the permissions system <django.contrib.auth.models.Permission` in
  119. Django's authentication framework uses a
  120. :class:`~django.contrib.auth.models.Permission` model with a foreign
  121. key to :class:`~django.contrib.contenttypes.models.ContentType`; this lets
  122. :class:`~django.contrib.auth.models.Permission` represent concepts like
  123. "can add blog entry" or "can delete news story".
  124. The ``ContentTypeManager``
  125. --------------------------
  126. .. class:: models.ContentTypeManager
  127. :class:`~django.contrib.contenttypes.models.ContentType` also has a custom
  128. manager, :class:`~django.contrib.contenttypes.models.ContentTypeManager`,
  129. which adds the following methods:
  130. .. method:: models.ContentTypeManager.clear_cache()
  131. Clears an internal cache used by
  132. :class:`~django.contrib.contenttypes.models.ContentType` to keep track
  133. of which models for which it has created
  134. :class:`django.contrib.contenttypes.models.ContentType` instances. You
  135. probably won't ever need to call this method yourself; Django will call
  136. it automatically when it's needed.
  137. .. method:: models.ContentTypeManager.get_for_model(model)
  138. Takes either a model class or an instance of a model, and returns the
  139. :class:`~django.contrib.contenttypes.models.ContentType` instance
  140. representing that model.
  141. The :meth:`~models.ContentTypeManager.get_for_model()` method is especially useful when you know you
  142. need to work with a :class:`ContentType <django.contrib.contenttypes.models.ContentType>` but don't want to go to the
  143. trouble of obtaining the model's metadata to perform a manual lookup::
  144. >>> from django.contrib.auth.models import User
  145. >>> user_type = ContentType.objects.get_for_model(User)
  146. >>> user_type
  147. <ContentType: user>
  148. .. _generic-relations:
  149. Generic relations
  150. =================
  151. Adding a foreign key from one of your own models to
  152. :class:`~django.contrib.contenttypes.models.ContentType` allows your model to
  153. effectively tie itself to another model class, as in the example of the
  154. :class:`~django.contrib.auth.models.Permission` model above. But it's possible
  155. to go one step further and use
  156. :class:`~django.contrib.contenttypes.models.ContentType` to enable truly
  157. generic (sometimes called "polymorphic") relationships between models.
  158. A simple example is a tagging system, which might look like this::
  159. from django.db import models
  160. from django.contrib.contenttypes.models import ContentType
  161. from django.contrib.contenttypes import generic
  162. class TaggedItem(models.Model):
  163. tag = models.SlugField()
  164. content_type = models.ForeignKey(ContentType)
  165. object_id = models.PositiveIntegerField()
  166. content_object = generic.GenericForeignKey('content_type', 'object_id')
  167. def __unicode__(self):
  168. return self.tag
  169. A normal :class:`~django.db.models.fields.related.ForeignKey` can only "point
  170. to" one other model, which means that if the ``TaggedItem`` model used a
  171. :class:`~django.db.models.fields.related.ForeignKey` it would have to
  172. choose one and only one model to store tags for. The contenttypes
  173. application provides a special field type --
  174. :class:`django.contrib.contenttypes.generic.GenericForeignKey` -- which
  175. works around this and allows the relationship to be with any
  176. model. There are three parts to setting up a
  177. :class:`~django.contrib.contenttypes.generic.GenericForeignKey`:
  178. 1. Give your model a :class:`~django.db.models.fields.related.ForeignKey`
  179. to :class:`~django.contrib.contenttypes.models.ContentType`.
  180. 2. Give your model a field that can store a primary-key value from the
  181. models you'll be relating to. (For most models, this means an
  182. :class:`~django.db.models.fields.IntegerField` or
  183. :class:`~django.db.models.fields.PositiveIntegerField`.)
  184. This field must be of the same type as the primary key of the models
  185. that will be involved in the generic relation. For example, if you use
  186. :class:`~django.db.models.fields.IntegerField`, you won't be able to
  187. form a generic relation with a model that uses a
  188. :class:`~django.db.models.fields.CharField` as a primary key.
  189. 3. Give your model a
  190. :class:`~django.contrib.contenttypes.generic.GenericForeignKey`, and
  191. pass it the names of the two fields described above. If these fields
  192. are named "content_type" and "object_id", you can omit this -- those
  193. are the default field names
  194. :class:`~django.contrib.contenttypes.generic.GenericForeignKey` will
  195. look for.
  196. This will enable an API similar to the one used for a normal
  197. :class:`~django.db.models.fields.related.ForeignKey`;
  198. each ``TaggedItem`` will have a ``content_object`` field that returns the
  199. object it's related to, and you can also assign to that field or use it when
  200. creating a ``TaggedItem``::
  201. >>> from django.contrib.auth.models import User
  202. >>> guido = User.objects.get(username='Guido')
  203. >>> t = TaggedItem(content_object=guido, tag='bdfl')
  204. >>> t.save()
  205. >>> t.content_object
  206. <User: Guido>
  207. Due to the way :class:`~django.contrib.contenttypes.generic.GenericForeignKey`
  208. is implemented, you cannot use such fields directly with filters (``filter()``
  209. and ``exclude()``, for example) via the database API. They aren't normal field
  210. objects. These examples will *not* work::
  211. # This will fail
  212. >>> TaggedItem.objects.filter(content_object=guido)
  213. # This will also fail
  214. >>> TaggedItem.objects.get(content_object=guido)
  215. Reverse generic relations
  216. -------------------------
  217. If you know which models you'll be using most often, you can also add
  218. a "reverse" generic relationship to enable an additional API. For example::
  219. class Bookmark(models.Model):
  220. url = models.URLField()
  221. tags = generic.GenericRelation(TaggedItem)
  222. ``Bookmark`` instances will each have a ``tags`` attribute, which can
  223. be used to retrieve their associated ``TaggedItems``::
  224. >>> b = Bookmark(url='http://www.djangoproject.com/')
  225. >>> b.save()
  226. >>> t1 = TaggedItem(content_object=b, tag='django')
  227. >>> t1.save()
  228. >>> t2 = TaggedItem(content_object=b, tag='python')
  229. >>> t2.save()
  230. >>> b.tags.all()
  231. [<TaggedItem: django>, <TaggedItem: python>]
  232. Just as :class:`django.contrib.contenttypes.generic.GenericForeignKey`
  233. accepts the names of the content-type and object-ID fields as
  234. arguments, so too does ``GenericRelation``; if the model which has the
  235. generic foreign key is using non-default names for those fields, you
  236. must pass the names of the fields when setting up a
  237. ``GenericRelation`` to it. For example, if the ``TaggedItem`` model
  238. referred to above used fields named ``content_type_fk`` and
  239. ``object_primary_key`` to create its generic foreign key, then a
  240. ``GenericRelation`` back to it would need to be defined like so::
  241. tags = generic.GenericRelation(TaggedItem, content_type_field='content_type_fk', object_id_field='object_primary_key')
  242. Of course, if you don't add the reverse relationship, you can do the
  243. same types of lookups manually::
  244. >>> b = Bookmark.objects.get(url='http://www.djangoproject.com/')
  245. >>> bookmark_type = ContentType.objects.get_for_model(b)
  246. >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id,
  247. ... object_id=b.id)
  248. [<TaggedItem: django>, <TaggedItem: python>]
  249. Note that if the model in a
  250. :class:`~django.contrib.contenttypes.generic.GenericRelation` uses a
  251. non-default value for ``ct_field`` or ``fk_field`` in its
  252. :class:`~django.contrib.contenttypes.generic.GenericForeignKey` (e.g. the
  253. :mod:`django.contrib.comments` app uses ``ct_field="object_pk"``),
  254. you'll need to set ``content_type_field`` and/or ``object_id_field`` in
  255. the :class:`~django.contrib.contenttypes.generic.GenericRelation` to
  256. match the ``ct_field`` and ``fk_field``, respectively, in the
  257. :class:`~django.contrib.contenttypes.generic.GenericForeignKey`::
  258. comments = generic.GenericRelation(Comment, object_id_field="object_pk")
  259. Note also, that if you delete an object that has a
  260. :class:`~django.contrib.contenttypes.generic.GenericRelation`, any objects
  261. which have a :class:`~django.contrib.contenttypes.generic.GenericForeignKey`
  262. pointing at it will be deleted as well. In the example above, this means that
  263. if a ``Bookmark`` object were deleted, any ``TaggedItem`` objects pointing at
  264. it would be deleted at the same time.
  265. Generic relations and aggregation
  266. ---------------------------------
  267. :doc:`Django's database aggregation API </topics/db/aggregation>`
  268. doesn't work with a
  269. :class:`~django.contrib.contenttypes.generic.GenericRelation`. For example, you
  270. might be tempted to try something like::
  271. Bookmark.objects.aggregate(Count('tags'))
  272. This will not work correctly, however. The generic relation adds extra filters
  273. to the queryset to ensure the correct content type, but the ``aggregate`` method
  274. doesn't take them into account. For now, if you need aggregates on generic
  275. relations, you'll need to calculate them without using the aggregation API.
  276. Generic relations in forms and admin
  277. ------------------------------------
  278. :mod:`django.contrib.contenttypes.generic` provides both a
  279. :class:`~django.contrib.contenttypes.generic.GenericInlineFormSet`
  280. and :class:`~django.contrib.contenttypes.generic.GenericInlineModelAdmin`.
  281. This enables the use of generic relations in forms and the admin. See the
  282. :doc:`model formset </topics/forms/modelforms>` and
  283. :doc:`admin </ref/contrib/admin/index>` documentation for more information.
  284. .. class:: generic.GenericInlineModelAdmin
  285. The :class:`~django.contrib.contenttypes.generic.GenericInlineModelAdmin`
  286. class inherits all properties from an
  287. :class:`~django.contrib.admin.options.InlineModelAdmin` class. However,
  288. it adds a couple of its own for working with the generic relation:
  289. .. attribute:: generic.GenericInlineModelAdmin.ct_field
  290. The name of the
  291. :class:`~django.contrib.contenttypes.models.ContentType` foreign key
  292. field on the model. Defaults to ``content_type``.
  293. .. attribute:: generic.GenericInlineModelAdmin.ct_fk_field
  294. The name of the integer field that represents the ID of the related
  295. object. Defaults to ``object_id``.