contenttypes.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. ==========================
  2. The contenttypes framework
  3. ==========================
  4. Django includes a "contenttypes" application that can track all of
  5. the models installed in your Django-powered project, providing a
  6. high-level, generic interface for working with your models.
  7. Overview
  8. ========
  9. At the heart of the contenttypes application is the ``ContentType``
  10. model, which lives at
  11. ``django.contrib.contenttypes.models.ContentType``. Instances of
  12. ``ContentType`` represent and store information about the models
  13. installed in your project, and new instances of ``ContentType`` are
  14. automatically created whenever new models are installed.
  15. Instances of ``ContentType`` have methods for returning the model
  16. classes they represent and for querying objects from those models.
  17. ``ContentType`` also has a `custom manager`_ that adds methods for
  18. working with ``ContentType`` and for obtaining instances of
  19. ``ContentType`` for a particular model.
  20. Relations between your models and ``ContentType`` can also be used to
  21. enable "generic" relationships between an instance of one of your
  22. models and instances of any model you have installed.
  23. .. _custom manager: ../model-api/#custom-managers
  24. Installing the contenttypes framework
  25. =====================================
  26. The contenttypes framework is included in the default
  27. ``INSTALLED_APPS`` list created by ``django-admin.py startproject``,
  28. but if you've removed it or if you manually set up your
  29. ``INSTALLED_APPS`` list, you can enable it by adding
  30. ``'django.contrib.contenttypes'`` to your ``INSTALLED_APPS`` setting.
  31. It's generally a good idea to have the contenttypes framework
  32. installed; several of Django's other bundled applications require it:
  33. * The admin application uses it to log the history of each object
  34. added or changed through the admin interface.
  35. * Django's `authentication framework`_ uses it to tie user permissions
  36. to specific models.
  37. * Django's comments system (``django.contrib.comments``) uses it to
  38. "attach" comments to any installed model.
  39. .. _authentication framework: ../authentication/
  40. The ``ContentType`` model
  41. =========================
  42. Each instance of ``ContentType`` has three fields which, taken
  43. together, uniquely describe an installed model:
  44. ``app_label``
  45. The name of the application the model is part of. This is taken from
  46. the ``app_label`` attribute of the model, and includes only the *last*
  47. part of the application's Python import path;
  48. "django.contrib.contenttypes", for example, becomes an ``app_label``
  49. of "contenttypes".
  50. ``model``
  51. The name of the model class.
  52. ``name``
  53. The human-readable name of the model. This is taken from
  54. `the verbose_name attribute`_ of the model.
  55. Let's look at an example to see how this works. If you already have
  56. the contenttypes application installed, and then add `the sites application`_
  57. to your ``INSTALLED_APPS`` setting and run ``manage.py syncdb`` to install it,
  58. the model ``django.contrib.sites.models.Site`` will be installed into your
  59. database. Along with it a new instance of ``ContentType`` will be created with
  60. the following values:
  61. * ``app_label`` will be set to ``'sites'`` (the last part of the Python
  62. path "django.contrib.sites").
  63. * ``model`` will be set to ``'site'``.
  64. * ``name`` will be set to ``'site'``.
  65. .. _the verbose_name attribute: ../model-api/#verbose_name
  66. .. _the sites application: ../sites/
  67. Methods on ``ContentType`` instances
  68. ====================================
  69. Each ``ContentType`` instance has methods that allow you to get from a
  70. ``ContentType`` instance to the model it represents, or to retrieve objects
  71. from that model:
  72. ``get_object_for_this_type(**kwargs)``
  73. Takes a set of valid `lookup arguments`_ for the model the
  74. ``ContentType`` represents, and does `a get() lookup`_ on that
  75. model, returning the corresponding object.
  76. ``model_class()``
  77. Returns the model class represented by this ``ContentType``
  78. instance.
  79. For example, we could look up the ``ContentType`` for the ``User`` model::
  80. >>> from django.contrib.contenttypes.models import ContentType
  81. >>> user_type = ContentType.objects.get(app_label="auth", model="user")
  82. >>> user_type
  83. <ContentType: user>
  84. And then use it to query for a particular ``User``, or to get access
  85. to the ``User`` model class::
  86. >>> user_type.model_class()
  87. <class 'django.contrib.auth.models.User'>
  88. >>> user_type.get_object_for_this_type(username='Guido')
  89. <User: Guido>
  90. Together, ``get_object_for_this_type`` and ``model_class`` enable two
  91. extremely important use cases:
  92. 1. Using these methods, you can write high-level generic code that
  93. performs queries on any installed model -- instead of importing and
  94. using a single specific model class, you can pass an ``app_label``
  95. and ``model`` into a ``ContentType`` lookup at runtime, and then
  96. work with the model class or retrieve objects from it.
  97. 2. You can relate another model to ``ContentType`` as a way of tying
  98. instances of it to particular model classes, and use these methods
  99. to get access to those model classes.
  100. Several of Django's bundled applications make use of the latter
  101. technique. For example, `the permissions system`_ in Django's
  102. authentication framework uses a ``Permission`` model with a foreign
  103. key to ``ContentType``; this lets ``Permission`` represent concepts
  104. like "can add blog entry" or "can delete news story".
  105. .. _lookup arguments: ../db-api/#field-lookups
  106. .. _a get() lookup: ../db-api/#get-kwargs
  107. .. _the permissions system: ../authentication/#permissions
  108. The ``ContentTypeManager``
  109. --------------------------
  110. ``ContentType`` also has a custom manager, ``ContentTypeManager``,
  111. which adds the following methods:
  112. ``clear_cache()``
  113. Clears an internal cache used by ``ContentType`` to keep track of which
  114. models for which it has created ``ContentType`` instances. You probably
  115. won't ever need to call this method yourself; Django will call it
  116. automatically when it's needed.
  117. ``get_for_model(model)``
  118. Takes either a model class or an instance of a model, and returns the
  119. ``ContentType`` instance representing that model.
  120. The ``get_for_model`` method is especially useful when you know you
  121. need to work with a ``ContentType`` but don't want to go to the
  122. trouble of obtaining the model's metadata to perform a manual lookup::
  123. >>> from django.contrib.auth.models import User
  124. >>> user_type = ContentType.objects.get_for_model(User)
  125. >>> user_type
  126. <ContentType: user>
  127. Generic relations
  128. =================
  129. Adding a foreign key from one of your own models to ``ContentType``
  130. allows your model to effectively tie itself to another model class, as
  131. in the example of the ``Permission`` model above. But it's possible to
  132. go one step further and use ``ContentType`` to enable truly generic
  133. (sometimes called "polymorphic") relationships between models.
  134. A simple example is a tagging system, which might look like this::
  135. from django.db import models
  136. from django.contrib.contenttypes.models import ContentType
  137. from django.contrib.contenttypes import generic
  138. class TaggedItem(models.Model):
  139. tag = models.SlugField()
  140. content_type = models.ForeignKey(ContentType)
  141. object_id = models.PositiveIntegerField()
  142. content_object = generic.GenericForeignKey('content_type', 'object_id')
  143. def __unicode__(self):
  144. return self.tag
  145. A normal ``ForeignKey`` can only "point to" one other model, which
  146. means that if the ``TaggedItem`` model used a ``ForeignKey`` it would have to
  147. choose one and only one model to store tags for. The contenttypes
  148. application provides a special field type --
  149. ``django.contrib.contenttypes.generic.GenericForeignKey`` -- which
  150. works around this and allows the relationship to be with any
  151. model. There are three parts to setting up a ``GenericForeignKey``:
  152. 1. Give your model a ``ForeignKey`` to ``ContentType``.
  153. 2. Give your model a field that can store a primary-key value from the
  154. models you'll be relating to. (For most models, this means an
  155. ``IntegerField`` or ``PositiveIntegerField``.)
  156. This field must be of the same type as the primary key of the models
  157. that will be involved in the generic relation. For example, if you use
  158. ``IntegerField``, you won't be able to form a generic relation with a
  159. model that uses a ``CharField`` as a primary key.
  160. 3. Give your model a ``GenericForeignKey``, and pass it the names of
  161. the two fields described above. If these fields are named
  162. "content_type" and "object_id", you can omit this -- those are the
  163. default field names ``GenericForeignKey`` will look for.
  164. This will enable an API similar to the one used for a normal ``ForeignKey``;
  165. each ``TaggedItem`` will have a ``content_object`` field that returns the
  166. object it's related to, and you can also assign to that field or use it when
  167. creating a ``TaggedItem``::
  168. >>> from django.contrib.auth.models import User
  169. >>> guido = User.objects.get(username='Guido')
  170. >>> t = TaggedItem(content_object=guido, tag='bdfl')
  171. >>> t.save()
  172. >>> t.content_object
  173. <User: Guido>
  174. Due to the way ``GenericForeignKey`` is implemeneted, you cannot use such
  175. fields directly with filters (``filter()`` and ``exclude()``, for example) via
  176. the database API. They aren't normal field objects. These examples will *not*
  177. work::
  178. # This will fail
  179. >>> TaggedItem.objects.filter(content_object=guido)
  180. # This will also fail
  181. >>> TaggedItem.objects.get(content_object=guido)
  182. Reverse generic relations
  183. -------------------------
  184. If you know which models you'll be using most often, you can also add
  185. a "reverse" generic relationship to enable an additional API. For example::
  186. class Bookmark(models.Model):
  187. url = models.URLField()
  188. tags = generic.GenericRelation(TaggedItem)
  189. ``Bookmark`` instances will each have a ``tags`` attribute, which can
  190. be used to retrieve their associated ``TaggedItems``::
  191. >>> b = Bookmark(url='http://www.djangoproject.com/')
  192. >>> b.save()
  193. >>> t1 = TaggedItem(content_object=b, tag='django')
  194. >>> t1.save()
  195. >>> t2 = TaggedItem(content_object=b, tag='python')
  196. >>> t2.save()
  197. >>> b.tags.all()
  198. [<TaggedItem: django>, <TaggedItem: python>]
  199. If you don't add the reverse relationship, you can do the lookup manually::
  200. >>> b = Bookmark.objects.get(url='http://www.djangoproject.com/)
  201. >>> bookmark_type = ContentType.objects.get_for_model(b)
  202. >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id,
  203. ... object_id=b.id)
  204. [<TaggedItem: django>, <TaggedItem: python>]
  205. Note that if you delete an object that has a ``GenericRelation``, any objects
  206. which have a ``GenericForeignKey`` pointing at it will be deleted as well. In
  207. the example above, this means that if a ``Bookmark`` object were deleted, any
  208. ``TaggedItem`` objects pointing at it would be deleted at the same time.
  209. Generic relations in forms and admin
  210. ------------------------------------
  211. ``django.contrib.contenttypes.generic`` provides both a ``GenericInlineFormSet``
  212. and ``GenericInlineModelAdmin``. This enables the use of generic relations in
  213. forms and the admin. See the `model formset`_ and `admin`_ documentation for
  214. more information.
  215. ``GenericInlineModelAdmin`` options
  216. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  217. The ``GenericInlineModelAdmin`` class inherits all properties from an
  218. ``InlineModelAdmin`` class. However, it adds a couple of its own for working
  219. with the generic relation:
  220. * ``ct_field`` - The name of the ``ContentType`` foreign key field on the
  221. model. Defaults to ``content_type``.
  222. * ``ct_fk_field`` - The name of the integer field that represents the ID
  223. of the related object. Defaults to ``object_id``.
  224. .. _model formset: ../modelforms/
  225. .. _admin: ../admin/