The contenttypes framework¶
Django includes a
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.
At the heart of the contenttypes application is the
ContentType model, which lives at
django.contrib.contenttypes.models.ContentType. Instances of
ContentType represent and store
information about the models installed in your project, and new instances of
ContentType are automatically
created whenever new models are installed.
methods for returning the model classes they represent and for querying objects
from those models.
also has a custom manager that adds methods for
ContentType and for
obtaining instances of
for a particular model.
Relations between your models and
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
INSTALLED_APPS list created by
but if you’ve removed it or if you manually set up your
INSTALLED_APPS list, you can enable it by adding
'django.contrib.contenttypes' to your
It’s generally a good idea to have the contenttypes framework installed; several of Django’s other bundled applications require it:
Each instance of
ContentTypehas three fields which, taken together, uniquely describe an installed model:
The name of the application the model is part of. This is taken from the
app_labelattribute of the model, and includes only the last part of the application’s Python import path; “django.contrib.contenttypes”, for example, becomes an
The name of the model class.
Let’s look at an example to see how this works. If you already have
contenttypes application installed, and then add
the sites application to your
INSTALLED_APPS setting and run
manage.py syncdb to install it,
django.contrib.sites.models.Site will be installed into
your database. Along with it a new instance of
ContentType will be
created with the following values:
>>> from django.contrib.contenttypes.models import ContentType >>> user_type = ContentType.objects.get(app_label="auth", model="user") >>> user_type <ContentType: user>
And then use it to query for a particular
User, or to get access
User model class:
>>> user_type.model_class() <class 'django.contrib.auth.models.User'> >>> user_type.get_object_for_this_type(username='Guido') <User: Guido>
- 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
ContentTypelookup at runtime, and then work with the model class or retrieve objects from it.
- You can relate another model to
ContentTypeas 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.
the permissions system in
Django’s authentication framework uses a
Permission model with a foreign
ContentType; this lets
Permission represent concepts like
“can add blog entry” or “can delete news story”.
Clears an internal cache used by
ContentTypeto keep track of models for which it has created
ContentTypeinstances. You probably won’t ever need to call this method yourself; Django will call it automatically when it’s needed.
Takes either a model class or an instance of a model, and returns the
ContentTypeinstance representing that model.
Takes a variadic number of model classes, and returns a dictionary mapping the model classes to the
ContentTypeinstances representing them.
>>> from django.contrib.auth.models import User >>> user_type = ContentType.objects.get_for_model(User) >>> user_type <ContentType: user>
Prior to Django 1.5,
always returned the
associated with the concrete model of the specified one(s). That means there
was no way to retrieve the
ContentType of a proxy model
using those methods. As of Django 1.5 you can now pass a boolean flag –
for_concrete_models respectively – to specify
wether or not you want to retrieve the
ContentType for the concrete or
Adding a foreign key from one of your own models to
ContentType allows your model to
effectively tie itself to another model class, as in the example of the
Permission model above. But it’s possible
to go one step further and use
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.models import ContentType from django.contrib.contenttypes import generic class TaggedItem(models.Model): tag = models.SlugField() content_type = models.ForeignKey(ContentType) object_id = models.PositiveIntegerField() content_object = generic.GenericForeignKey('content_type', 'object_id') def __unicode__(self): return self.tag
ForeignKey can only “point
to” one other model, which means that if the
TaggedItem model used a
ForeignKey it would have to
choose one and only one model to store tags for. The contenttypes
application provides a special field type (
works around this and allows the relationship to be with any
There are three parts to setting up a
- Give your model a
ContentType. The usual name for this field is “content_type”.
- 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
PositiveIntegerField. The usual name for this field is “object_id”.
- Give your model a
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
GenericForeignKeywill look for.
- Give your model a
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
For example, if you want to allow generic relations to models with either
CharField primary key fields, you
CharField for the
“object_id” field on your model since integers can be coerced to
For maximum flexibility you can use a
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.
Serializing references to
If you’re serializing data (for example, when generating
fixtures) from a model that implements
generic relations, you should probably be using a natural key to uniquely
objects. See natural keys and
dumpdata --natural for more information.
This will enable an API similar to the one used for a normal
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
>>> 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
is implemented, you cannot use such fields directly with filters (
exclude(), for example) via the database API. Because a
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)
Reverse generic relations¶
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:
class Bookmark(models.Model): url = models.URLField() tags = generic.GenericRelation(TaggedItem)
Bookmark instances will each have a
tags attribute, which can
be used to retrieve their associated
>>> 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() [<TaggedItem: django>, <TaggedItem: python>]
accepts the names of the content-type and object-ID fields as
arguments, so too does
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
GenericRelation to it. For example, if the
referred to above used fields named
object_primary_key to create its generic foreign key, then a
GenericRelation back to it would need to be defined like so:
tags = generic.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) [<TaggedItem: django>, <TaggedItem: python>]
Note that if the model in a
GenericRelation uses a
non-default value for
fk_field in its
GenericForeignKey (e.g. the
django.contrib.comments app uses
you’ll need to set
fk_field, respectively, in the
comments = generic.GenericRelation(Comment, object_id_field="object_pk")
Note also, that if you delete an object that has a
GenericRelation, any objects
which have a
pointing at it will be deleted as well. In the example above, this means that
Bookmark object were deleted, any
TaggedItem objects pointing at
it would be deleted at the same time.
GenericForeignKey does not accept
on_delete argument to customize this
behavior; if desired, you can avoid the cascade-deletion simply by not using
GenericRelation, and alternate
behavior can be provided via the
Generic relations and aggregation¶
This will not work correctly, however. The generic relation adds extra filters
to the queryset to ensure the correct content type, but the
aggregate() method doesn’t take them
into account. For now, if you need aggregates on generic relations, you’ll
need to calculate them without using the aggregation API.
Generic relations in forms and admin¶
django.contrib.contenttypes.generic module provides:
- A formset factory,
generic_inlineformset_factory(), for use with
The name of the integer field that represents the ID of the related object. Defaults to
GenericInlineModelAdminwith stacked and tabular layouts, respectively.
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)¶
You must provide
object_idif they different from the defaults,
object_idrespectively. Other parameters are similar to those documented in