Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/docs/ref/contrib/contenttypes.txt
blob: 0d75739e48569584cb4e5311f5a29897b345f9ac (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
==========================
The contenttypes framework
==========================

.. module:: django.contrib.contenttypes
   :synopsis: Provides generic interface to installed models.

Django includes a :mod:`~django.contrib.contenttypes` application that can
track all of the models installed in your Django-powered project, providing a
high-level, generic interface for working with your models.

Overview
========

At the heart of the contenttypes application is the
:class:`~django.contrib.contenttypes.models.ContentType` model, which lives at
``django.contrib.contenttypes.models.ContentType``. Instances of
:class:`~django.contrib.contenttypes.models.ContentType` represent and store
information about the models installed in your project, and new instances of
:class:`~django.contrib.contenttypes.models.ContentType` are automatically
created whenever new models are installed.

Instances of :class:`~django.contrib.contenttypes.models.ContentType` have
methods for returning the model classes they represent and for querying objects
from those models. :class:`~django.contrib.contenttypes.models.ContentType`
also has a :ref:`custom manager <custom-managers>` that adds methods for
working with :class:`~django.contrib.contenttypes.models.ContentType` and for
obtaining instances of :class:`~django.contrib.contenttypes.models.ContentType`
for a particular model.

Relations between your models and
:class:`~django.contrib.contenttypes.models.ContentType` can also be used to
enable "generic" relationships between an instance of one of your
models and instances of any model you have installed.

Installing the contenttypes framework
=====================================

The contenttypes framework is included in the default
:setting:`INSTALLED_APPS` list created by ``django-admin startproject``,
but if you've removed it or if you manually set up your
:setting:`INSTALLED_APPS` list, you can enable it by adding
``'django.contrib.contenttypes'`` to your :setting:`INSTALLED_APPS` setting.

It's generally a good idea to have the contenttypes framework
installed; several of Django's other bundled applications require it:

* The admin application uses it to log the history of each object
  added or changed through the admin interface.

* Django's :mod:`authentication framework <django.contrib.auth>` uses it
  to tie user permissions to specific models.

.. currentmodule:: django.contrib.contenttypes.models

The ``ContentType`` model
=========================

.. class:: ContentType

    Each instance of :class:`~django.contrib.contenttypes.models.ContentType`
    has two fields which, taken together, uniquely describe an installed
    model:

    .. attribute:: app_label

        The name of the application the model is part of. This is taken from
        the :attr:`app_label` attribute of the model, and includes only the
        *last* part of the application's Python import path;
        "django.contrib.contenttypes", for example, becomes an
        :attr:`app_label` of "contenttypes".

    .. attribute:: model

        The name of the model class.

    Additionally, the following property is available:

    .. attribute:: name

        The human-readable name of the content type. This is taken from the
        :attr:`verbose_name <django.db.models.Field.verbose_name>`
        attribute of the model.

Let's look at an example to see how this works. If you already have
the :mod:`~django.contrib.contenttypes` application installed, and then add
:mod:`the sites application <django.contrib.sites>` to your
:setting:`INSTALLED_APPS` setting and run ``manage.py migrate`` to install it,
the model :class:`django.contrib.sites.models.Site` will be installed into
your database. Along with it a new instance of
:class:`~django.contrib.contenttypes.models.ContentType` will be
created with the following values:

* :attr:`~django.contrib.contenttypes.models.ContentType.app_label`
  will be set to ``'sites'`` (the last part of the Python
  path "django.contrib.sites").

* :attr:`~django.contrib.contenttypes.models.ContentType.model`
  will be set to ``'site'``.

Methods on ``ContentType`` instances
====================================

Each :class:`~django.contrib.contenttypes.models.ContentType` instance has
methods that allow you to get from a
:class:`~django.contrib.contenttypes.models.ContentType` instance to the
model it represents, or to retrieve objects from that model:

.. method:: ContentType.get_object_for_this_type(**kwargs)

    Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the
    model the :class:`~django.contrib.contenttypes.models.ContentType`
    represents, and does
    :meth:`a get() lookup <django.db.models.query.QuerySet.get>`
    on that model, returning the corresponding object.

.. method:: ContentType.model_class()

    Returns the model class represented by this
    :class:`~django.contrib.contenttypes.models.ContentType` instance.

For example, we could look up the
:class:`~django.contrib.contenttypes.models.ContentType` for the
:class:`~django.contrib.auth.models.User` model::

    >>> from django.contrib.contenttypes.models import ContentType
    >>> ContentType.objects.get(app_label="auth", model="user")
    <ContentType: user>

And then use it to query for a particular
:class:`~django.contrib.auth.models.User`, or to get access
to the ``User`` model class::

    >>> user_type.model_class()
    <class 'django.contrib.auth.models.User'>
    >>> user_type.get_object_for_this_type(username='Guido')
    <User: Guido>

Together,
:meth:`~django.contrib.contenttypes.models.ContentType.get_object_for_this_type`
and :meth:`~django.contrib.contenttypes.models.ContentType.model_class` enable
two extremely important use cases:

1. Using these methods, you can write high-level generic code that
   performs queries on any installed model -- instead of importing and
   using a single specific model class, you can pass an ``app_label`` and
   ``model`` into a
   :class:`~django.contrib.contenttypes.models.ContentType` lookup at
   runtime, and then work with the model class or retrieve objects from it.

2. You can relate another model to
   :class:`~django.contrib.contenttypes.models.ContentType` as a way of
   tying instances of it to particular model classes, and use these methods
   to get access to those model classes.

Several of Django's bundled applications make use of the latter technique.
For example,
:class:`the permissions system <django.contrib.auth.models.Permission>` in
Django's authentication framework uses a
:class:`~django.contrib.auth.models.Permission` model with a foreign
key to :class:`~django.contrib.contenttypes.models.ContentType`; this lets
:class:`~django.contrib.auth.models.Permission` represent concepts like
"can add blog entry" or "can delete news story".

The ``ContentTypeManager``
--------------------------

.. class:: ContentTypeManager

    :class:`~django.contrib.contenttypes.models.ContentType` also has a custom
    manager, :class:`~django.contrib.contenttypes.models.ContentTypeManager`,
    which adds the following methods:

    .. method:: clear_cache()

        Clears an internal cache used by
        :class:`~django.contrib.contenttypes.models.ContentType` to keep track
        of models for which it has created
        :class:`~django.contrib.contenttypes.models.ContentType` instances. You
        probably won't ever need to call this method yourself; Django will call
        it automatically when it's needed.

    .. method:: get_for_id(id)

        Lookup a :class:`~django.contrib.contenttypes.models.ContentType` by ID.
        Since this method uses the same shared cache as
        :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`,
        it's preferred to use this method over the usual
        ``ContentType.objects.get(pk=id)``

    .. method:: get_for_model(model, for_concrete_model=True)

        Takes either a model class or an instance of a model, and returns the
        :class:`~django.contrib.contenttypes.models.ContentType` instance
        representing that model. ``for_concrete_model=False`` allows fetching
        the :class:`~django.contrib.contenttypes.models.ContentType` of a proxy
        model.

    .. method:: get_for_models(*models, for_concrete_models=True)

        Takes a variadic number of model classes, and returns a dictionary
        mapping the model classes to the
        :class:`~django.contrib.contenttypes.models.ContentType` instances
        representing them. ``for_concrete_models=False`` allows fetching the
        :class:`~django.contrib.contenttypes.models.ContentType` of proxy
        models.

    .. method:: get_by_natural_key(app_label, model)

        Returns the :class:`~django.contrib.contenttypes.models.ContentType`
        instance uniquely identified by the given application label and model
        name. The primary purpose of this method is to allow
        :class:`~django.contrib.contenttypes.models.ContentType` objects to be
        referenced via a :ref:`natural key<topics-serialization-natural-keys>`
        during deserialization.

The :meth:`~ContentTypeManager.get_for_model()` method is especially
useful when you know you need to work with a
:class:`ContentType <django.contrib.contenttypes.models.ContentType>` but don't
want to go to the trouble of obtaining the model's metadata to perform a manual
lookup::

    >>> from django.contrib.auth.models import User
    >>> ContentType.objects.get_for_model(User)
    <ContentType: user>

.. module:: django.contrib.contenttypes.fields

.. _generic-relations:

Generic relations
=================

Adding a foreign key from one of your own models to
:class:`~django.contrib.contenttypes.models.ContentType` allows your model to
effectively tie itself to another model class, as in the example of the
:class:`~django.contrib.auth.models.Permission` model above. But it's possible
to go one step further and use
:class:`~django.contrib.contenttypes.models.ContentType` to enable truly
generic (sometimes called "polymorphic") relationships between models.

A simple example is a tagging system, which might look like this::

    from django.db import models
    from django.contrib.contenttypes.fields import GenericForeignKey
    from django.contrib.contenttypes.models import ContentType

    class TaggedItem(models.Model):
        tag = models.SlugField()
        content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
        object_id = models.PositiveIntegerField()
        content_object = GenericForeignKey('content_type', 'object_id')

        def __str__(self):              # __unicode__ on Python 2
            return self.tag

A normal :class:`~django.db.models.ForeignKey` can only "point
to" one other model, which means that if the ``TaggedItem`` model used a
:class:`~django.db.models.ForeignKey` it would have to
choose one and only one model to store tags for. The contenttypes
application provides a special field type (``GenericForeignKey``) which
works around this and allows the relationship to be with any
model:

.. class:: GenericForeignKey

    There are three parts to setting up a
    :class:`~django.contrib.contenttypes.fields.GenericForeignKey`:

    1. Give your model a :class:`~django.db.models.ForeignKey`
       to :class:`~django.contrib.contenttypes.models.ContentType`. The usual
       name for this field is "content_type".

    2. Give your model a field that can store primary key values from the
       models you'll be relating to. For most models, this means a
       :class:`~django.db.models.PositiveIntegerField`. The usual name
       for this field is "object_id".

    3. Give your model a
       :class:`~django.contrib.contenttypes.fields.GenericForeignKey`, and
       pass it the names of the two fields described above. If these fields
       are named "content_type" and "object_id", you can omit this -- those
       are the default field names
       :class:`~django.contrib.contenttypes.fields.GenericForeignKey` will
       look for.

    .. attribute:: GenericForeignKey.for_concrete_model

       If ``False``, the field will be able to reference proxy models. Default
       is ``True``. This mirrors the ``for_concrete_model`` argument to
       :meth:`~django.contrib.contenttypes.models.ContentTypeManager.get_for_model`.

.. admonition:: Primary key type compatibility

   The "object_id" field doesn't have to be the same type as the
   primary key fields on the related models, but their primary key values
   must be coercible to the same type as the "object_id" field by its
   :meth:`~django.db.models.Field.get_db_prep_value` method.

   For example, if you want to allow generic relations to models with either
   :class:`~django.db.models.IntegerField` or
   :class:`~django.db.models.CharField` primary key fields, you
   can use :class:`~django.db.models.CharField` for the
   "object_id" field on your model since integers can be coerced to
   strings by :meth:`~django.db.models.Field.get_db_prep_value`.

   For maximum flexibility you can use a
   :class:`~django.db.models.TextField` which doesn't have a
   maximum length defined, however this may incur significant performance
   penalties depending on your database backend.

   There is no one-size-fits-all solution for which field type is best. You
   should evaluate the models you expect to be pointing to and determine
   which solution will be most effective for your use case.

.. admonition:: Serializing references to ``ContentType`` objects

   If you're serializing data (for example, when generating
   :class:`~django.test.TransactionTestCase.fixtures`) from a model that implements
   generic relations, you should probably be using a natural key to uniquely
   identify related :class:`~django.contrib.contenttypes.models.ContentType`
   objects. See :ref:`natural keys<topics-serialization-natural-keys>` and
   :djadminopt:`dumpdata --natural-foreign <--natural-foreign>` for more
   information.

This will enable an API similar to the one used for a normal
:class:`~django.db.models.ForeignKey`;
each ``TaggedItem`` will have a ``content_object`` field that returns the
object it's related to, and you can also assign to that field or use it when
creating a ``TaggedItem``::

    >>> from django.contrib.auth.models import User
    >>> guido = User.objects.get(username='Guido')
    >>> t = TaggedItem(content_object=guido, tag='bdfl')
    >>> t.save()
    >>> t.content_object
    <User: Guido>

Due to the way :class:`~django.contrib.contenttypes.fields.GenericForeignKey`
is implemented, you cannot use such fields directly with filters (``filter()``
and ``exclude()``, for example) via the database API. Because a
:class:`~django.contrib.contenttypes.fields.GenericForeignKey` isn't a
normal field object, these examples will *not* work::

    # This will fail
    >>> TaggedItem.objects.filter(content_object=guido)
    # This will also fail
    >>> TaggedItem.objects.get(content_object=guido)

Likewise, :class:`~django.contrib.contenttypes.fields.GenericForeignKey`\s
does not appear in :class:`~django.forms.ModelForm`\s.

Reverse generic relations
-------------------------

.. class:: GenericRelation

    .. attribute:: related_query_name

        The relation on the related object back to this object doesn't exist by
        default. Setting ``related_query_name`` creates a relation from the
        related object back to this one. This allows querying and filtering
        from the related object.

If you know which models you'll be using most often, you can also add
a "reverse" generic relationship to enable an additional API. For example::

    from django.db import models
    from django.contrib.contenttypes.fields import GenericRelation

    class Bookmark(models.Model):
        url = models.URLField()
        tags = GenericRelation(TaggedItem)

``Bookmark`` instances will each have a ``tags`` attribute, which can
be used to retrieve their associated ``TaggedItems``::

    >>> b = Bookmark(url='https://www.djangoproject.com/')
    >>> b.save()
    >>> t1 = TaggedItem(content_object=b, tag='django')
    >>> t1.save()
    >>> t2 = TaggedItem(content_object=b, tag='python')
    >>> t2.save()
    >>> b.tags.all()
    <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>

Defining :class:`~django.contrib.contenttypes.fields.GenericRelation` with
``related_query_name`` set allows querying from the related object::

    tags = GenericRelation(TaggedItem, related_query_name='bookmarks')

This enables filtering, ordering, and other query operations on ``Bookmark``
from ``TaggedItem``::

    >>> # Get all tags belonging to books containing `django` in the url
    >>> TaggedItem.objects.filter(bookmarks__url__contains='django')
    <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>

Just as :class:`~django.contrib.contenttypes.fields.GenericForeignKey`
accepts the names of the content-type and object-ID fields as
arguments, so too does
:class:`~django.contrib.contenttypes.fields.GenericRelation`;
if the model which has the generic foreign key is using non-default names
for those fields, you must pass the names of the fields when setting up a
:class:`.GenericRelation` to it. For example, if the ``TaggedItem`` model
referred to above used fields named ``content_type_fk`` and
``object_primary_key`` to create its generic foreign key, then a
:class:`.GenericRelation` back to it would need to be defined like so::

    tags = GenericRelation(TaggedItem,
                           content_type_field='content_type_fk',
                           object_id_field='object_primary_key')

Of course, if you don't add the reverse relationship, you can do the
same types of lookups manually::

    >>> b = Bookmark.objects.get(url='https://www.djangoproject.com/')
    >>> bookmark_type = ContentType.objects.get_for_model(b)
    >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id,
    ...                           object_id=b.id)
    <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>

Note that if the model in a
:class:`~django.contrib.contenttypes.fields.GenericRelation` uses a
non-default value for ``ct_field`` or ``fk_field`` in its
:class:`~django.contrib.contenttypes.fields.GenericForeignKey` (for example, if
you had a ``Comment`` model that uses ``ct_field="object_pk"``),
you'll need to set ``content_type_field`` and/or ``object_id_field`` in
the :class:`~django.contrib.contenttypes.fields.GenericRelation` to
match the ``ct_field`` and ``fk_field``, respectively, in the
:class:`~django.contrib.contenttypes.fields.GenericForeignKey`::

    comments = fields.GenericRelation(Comment, object_id_field="object_pk")

Note also, that if you delete an object that has a
:class:`~django.contrib.contenttypes.fields.GenericRelation`, any objects
which have a :class:`~django.contrib.contenttypes.fields.GenericForeignKey`
pointing at it will be deleted as well. In the example above, this means that
if a ``Bookmark`` object were deleted, any ``TaggedItem`` objects pointing at
it would be deleted at the same time.

Unlike :class:`~django.db.models.ForeignKey`,
:class:`~django.contrib.contenttypes.fields.GenericForeignKey` does not accept
an :attr:`~django.db.models.ForeignKey.on_delete` argument to customize this
behavior; if desired, you can avoid the cascade-deletion simply by not using
:class:`~django.contrib.contenttypes.fields.GenericRelation`, and alternate
behavior can be provided via the :data:`~django.db.models.signals.pre_delete`
signal.

Generic relations and aggregation
---------------------------------

:doc:`Django's database aggregation API </topics/db/aggregation>` works with a
:class:`~django.contrib.contenttypes.fields.GenericRelation`. For example, you
can find out how many tags all the bookmarks have::

    >>> Bookmark.objects.aggregate(Count('tags'))
    {'tags__count': 3}

.. module:: django.contrib.contenttypes.forms

Generic relation in forms
-------------------------

The :mod:`django.contrib.contenttypes.forms` module provides:

* :class:`BaseGenericInlineFormSet`
* A formset factory, :func:`generic_inlineformset_factory`, for use with
  :class:`~django.contrib.contenttypes.fields.GenericForeignKey`.

.. class:: BaseGenericInlineFormSet

.. 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)

    Returns a ``GenericInlineFormSet`` using
    :func:`~django.forms.models.modelformset_factory`.

    You must provide ``ct_field`` and ``fk_field`` if they are different from
    the defaults, ``content_type`` and ``object_id`` respectively. Other
    parameters are similar to those documented in
    :func:`~django.forms.models.modelformset_factory` and
    :func:`~django.forms.models.inlineformset_factory`.

    The ``for_concrete_model`` argument corresponds to the
    :class:`~django.contrib.contenttypes.fields.GenericForeignKey.for_concrete_model`
    argument on ``GenericForeignKey``.

.. module:: django.contrib.contenttypes.admin

Generic relations in admin
--------------------------

The :mod:`django.contrib.contenttypes.admin` module provides
:class:`~django.contrib.contenttypes.admin.GenericTabularInline` and
:class:`~django.contrib.contenttypes.admin.GenericStackedInline` (subclasses of
:class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`)

These classes and functions enable the use of generic relations in forms
and the admin. See the :doc:`model formset </topics/forms/modelforms>` and
:ref:`admin <using-generic-relations-as-an-inline>` documentation for more
information.

.. class:: GenericInlineModelAdmin

    The :class:`~django.contrib.contenttypes.admin.GenericInlineModelAdmin`
    class inherits all properties from an
    :class:`~django.contrib.admin.InlineModelAdmin` class. However,
    it adds a couple of its own for working with the generic relation:

    .. attribute:: ct_field

        The name of the
        :class:`~django.contrib.contenttypes.models.ContentType` foreign key
        field on the model. Defaults to ``content_type``.

    .. attribute:: ct_fk_field

        The name of the integer field that represents the ID of the related
        object. Defaults to ``object_id``.

.. class:: GenericTabularInline
.. class:: GenericStackedInline

    Subclasses of :class:`GenericInlineModelAdmin` with stacked and tabular
    layouts, respectively.