The contenttypes framework
At the heart of the contenttypes application is theContentType
model, which lives atdjango.contrib.contenttypes.models.ContentType
. Instances of represent and storeinformation about the models installed in your project, and new instances ofContentType
are automaticallycreated whenever new models are installed.
Instances of havemethods for returning the model classes they represent and for querying objectsfrom those models. ContentType
also has a that adds methods forworking with ContentType
and forobtaining instances of for a particular model.
Relations between your models andContentType
can also be used toenable “generic” relationships between an instance of one of yourmodels and instances of any model you have installed.
The contenttypes framework is included in the default list created by django-admin startproject
,but if you’ve removed it or if you manually set up yourINSTALLED_APPS
list, you can enable it by adding'django.contrib.contenttypes'
to your setting.
It’s generally a good idea to have the contenttypes frameworkinstalled; several of Django’s other bundled applications require it:
- The admin application uses it to log the history of each objectadded or changed through the admin interface.
- Django’s
authentication framework
uses itto tie user permissions to specific models.
- class
ContentType
Each instance of
ContentType
has two fields which, taken together, uniquely describe an installedmodel:app_label
The name of the application the model is part of. This is taken fromthe
app_label
attribute of the model, and includes only thelast part of the application’s Python import path;django.contrib.contenttypes
, for example, becomes an ofcontenttypes
.- The name of the model class.
Additionally, the following property is available:
name
- The human-readable name of the content type. This is taken from the
verbose_name
attribute of the model.
Let’s look at an example to see how this works. If you already havethe application installed, and then addthe sites application
to your setting and run manage.py migrate
to install it,the model django.contrib.sites.models.Site
will be installed intoyour database. Along with it a new instance of will becreated with the following values:
app_label
will be set to'sites'
(the last part of the Pythonpathdjango.contrib.sites
).- will be set to
'site'
.
Each ContentType
instance hasmethods that allow you to get from a instance to themodel it represents, or to retrieve objects from that model:
ContentType.
getobject_for_this_type
(**kwargs_)Takes a set of valid for themodel the
ContentType
represents, and doeson that model, returning the corresponding object.- Returns the model class represented by this instance.
For example, we could look up theContentType
for the model:
And then use it to query for a particularUser
, or to get accessto 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,and model_class()
enabletwo extremely important use cases:
- Using these methods, you can write high-level generic code thatperforms queries on any installed model – instead of importing andusing a single specific model class, you can pass an
app_label
andmodel
into a lookup atruntime, and then work with the model class or retrieve objects from it. - You can relate another model to
ContentType
as a way oftying instances of it to particular model classes, and use these methodsto get access to those model classes.Several of Django’s bundled applications make use of the latter technique.For example, inDjango’s authentication framework uses aPermission
model with a foreignkey to ; this letsPermission
represent concepts like“can add blog entry” or “can delete news story”.
- class
ContentTypeManager
ContentType
also has a custommanager, ,which adds the following methods:clear_cache
()getfor_id
(_id)Takes either a model class or an instance of a model, and returns the instancerepresenting that model.
for_concrete_model=False
allows fetchingtheContentType
of a proxymodel.getfor_models
(*models, _for_concrete_models=True)Takes a variadic number of model classes, and returns a dictionarymapping the model classes to the
ContentType
instancesrepresenting them.for_concrete_models=False
allows fetching the of proxymodels.- Returns the instance uniquely identified by the given application label and modelname. The primary purpose of this method is to allow
ContentType
objects to bereferenced via a during deserialization.
The get_for_model()
method is especiallyuseful when you know you need to work with a but don’twant to go to the trouble of obtaining the model’s metadata to perform a manuallookup:
- >>> from django.contrib.auth.models import User
- >>> ContentType.objects.get_for_model(User)
- <ContentType: user>
Adding a foreign key from one of your own models toContentType
allows your model toeffectively tie itself to another model class, as in the example of the model above. But it’s possibleto go one step further and useContentType
to enable trulygeneric (sometimes called “polymorphic”) relationships between models.
For example, it could be used for a tagging system like so:
- from django.contrib.contenttypes.fields import GenericForeignKey
- from django.contrib.contenttypes.models import ContentType
- from django.db import models
- 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):
- return self.tag
A normal can only “pointto” one other model, which means that if the TaggedItem
model used aForeignKey
it would have tochoose one and only one model to store tags for. The contenttypesapplication provides a special field type (GenericForeignKey
) whichworks around this and allows the relationship to be with anymodel:
- class
GenericForeignKey
There are three parts to setting up a
GenericForeignKey
:- Give your model a to
ContentType
. The usualname for this field is “content_type”. - Give your model a field that can store primary key values from themodels you’ll be relating to. For most models, this means a. The usual namefor this field is “object_id”.
- Give your model a
GenericForeignKey
, andpass it the names of the two fields described above. If these fieldsare named “content_type” and “object_id”, you can omit this – thoseare the default field names willlook for. for_concrete_model
- If
False
, the field will be able to reference proxy models. DefaultisTrue
. This mirrors thefor_concrete_model
argument to.
- Give your model a to
Primary key type compatibility
The “object_id” field doesn’t have to be the same type as theprimary key fields on the related models, but their primary key valuesmust be coercible to the same type as the “object_id” field by itsget_db_prep_value()
method.
For example, if you want to allow generic relations to models with either orCharField
primary key fields, youcan use for the“object_id” field on your model since integers can be coerced tostrings by get_db_prep_value()
.
For maximum flexibility you can use a which doesn’t have amaximum length defined, however this may incur significant performancepenalties depending on your database backend.
There is no one-size-fits-all solution for which field type is best. Youshould evaluate the models you expect to be pointing to and determinewhich solution will be most effective for your use case.
Serializing references to ContentType
objects
If you’re serializing data (for example, when generatingfixtures
) from a model that implementsgeneric relations, you should probably be using a natural key to uniquelyidentify related objects. See natural keys and for more information.
This will enable an API similar to the one used for a normalForeignKey
;each TaggedItem
will have a content_object
field that returns theobject it’s related to, and you can also assign to that field or use it whencreating a TaggedItem
:
If the related object is deleted, the content_type
and object_id
fieldsremain set to their original values and the GenericForeignKey
returnsNone
:
- >>> guido.delete()
- >>> t.content_object # returns None
- # This will fail
- >>> TaggedItem.objects.filter(content_object=guido)
- # This will also fail
Likewise, sdoes not appear in ModelForm
s.
- class
GenericRelation
If you know which models you’ll be using most often, you can also adda “reverse” generic relationship to enable an additional API. For example:
- from django.contrib.contenttypes.fields import GenericRelation
- from django.db import models
- class Bookmark(models.Model):
- url = models.URLField()
- tags = GenericRelation(TaggedItem)
Bookmark
instances will each have a tags
attribute, which canbe used to retrieve their associated TaggedItems
:
Defining withrelated_query_name
set allows querying from the related object:
- tags = GenericRelation(TaggedItem, related_query_name='bookmark')
This enables filtering, ordering, and other query operations on Bookmark
from TaggedItem
:
- >>> # Get all tags belonging to bookmarks containing `django` in the url
- >>> TaggedItem.objects.filter(bookmark__url__contains='django')
- <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
Of course, if you don’t add the related_query_name
, you can do thesame types of lookups manually:
- >>> bookmarks = Bookmark.objects.filter(url__contains='django')
- >>> bookmark_type = ContentType.objects.get_for_model(Bookmark)
- >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id, object_id__in=bookmarks)
- <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>
Just as GenericForeignKey
accepts the names of the content-type and object-ID fields asarguments, so too does;if the model which has the generic foreign key is using non-default namesfor those fields, you must pass the names of the fields when setting up aGenericRelation
to it. For example, if the TaggedItem
modelreferred to above used fields named content_type_fk
andobject_primary_key
to create its generic foreign key, then a back to it would need to be defined like so:
Note also, that if you delete an object that has aGenericRelation
, any objectswhich have a pointing at it will be deleted as well. In the example above, this means thatif a Bookmark
object were deleted, any TaggedItem
objects pointing atit would be deleted at the same time.
Unlike ForeignKey
, does not acceptan on_delete
argument to customize thisbehavior; if desired, you can avoid the cascade-deletion by not using, and alternatebehavior can be provided via the pre_delete
signal.
works with aGenericRelation
. For example, youcan find out how many tags all the bookmarks have:
- >>> Bookmark.objects.aggregate(Count('tags'))
- {'tags__count': 3}
The module provides:
BaseGenericInlineFormSet
- A formset factory, , for use with
GenericForeignKey
. - class
BaseGenericInlineFormSet
genericinlineformset_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.
You must provide ct_field
and fk_field
if they are different fromthe defaults, content_type
and object_id
respectively. Otherparameters are similar to those documented inmodelformset_factory()
and.
The for_concrete_model
argument corresponds to thefor_concrete_model
argument on GenericForeignKey
.
The module providesGenericTabularInline
and (subclasses ofGenericInlineModelAdmin
)
These classes and functions enable the use of generic relations in formsand the admin. See the andadmin documentation for moreinformation.
- class
GenericInlineModelAdmin
The
GenericInlineModelAdmin
class inherits all properties from an class. However,it adds a couple of its own for working with the generic relation:class
GenericTabularInline
- class
GenericStackedInline