The contenttypes framework
Django includes a contenttypes
application that cantrack all of the models installed in your Django-powered project, providing ahigh-level, generic interface for working with your models.
概况
At the heart of the contenttypes application is theContentType
model, which lives atdjango.contrib.contenttypes.models.ContentType
. Instances ofContentType
represent and storeinformation about the models installed in your project, and new instances ofContentType
are automaticallycreated whenever new models are installed.
Instances of ContentType
havemethods for returning the model classes they represent and for querying objectsfrom those models. ContentType
also has a custom manager that adds methods forworking with ContentType
and forobtaining instances of ContentType
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.
Installing the contenttypes framework
The contenttypes framework is included in the defaultINSTALLED_APPS
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 INSTALLED_APPS
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.
The ContentType model
- class
ContentType
Each instance of
ContentType
has two fields which, taken together, uniquely describe an installedmodel:
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 contenttypes
application installed, and then addthe sites application
to yourINSTALLED_APPS
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 ofContentType
will becreated with the following values:
app_label
will be set to'sites'
(the last part of the Pythonpathdjango.contrib.sites
).model
will be set to'site'
.
Methods on ContentType instances
Each ContentType
instance hasmethods that allow you to get from aContentType
instance to themodel it represents, or to retrieve objects from that model:
ContentType.
getobject_for_this_type
(**kwargs_)Takes a set of valid lookup arguments for themodel the
ContentType
represents, and doesa get() lookup
on that model, returning the corresponding object.- Returns the model class represented by this
ContentType
instance.
For example, we could look up theContentType
for theUser
model:
- >>> 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 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,get_object_for_this_type()
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 aContentType
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,the permissions system
inDjango's authentication framework uses aPermission
model with a foreignkey toContentType
; this letsPermission
represent concepts like"can add blog entry" or "can delete news story".
The ContentTypeManager
- class
ContentTypeManager
ContentType
also has a custommanager,ContentTypeManager
,which adds the following methods:clear_cache
()Clears an internal cache used by
ContentType
to keep trackof models for which it has createdContentType
instances. Youprobably won't ever need to call this method yourself; Django will callit automatically when it's needed.Lookup a
ContentType
by ID.Since this method uses the same shared cache asget_for_model()
,it's preferred to use this method over the usualContentType.objects.get(pk=id)
Takes either a model class or an instance of a model, and returns the
ContentType
instancerepresenting that model.for_concrete_model=False
allows fetchingtheContentType
of a proxymodel.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 theContentType
of proxymodels.- Returns the
ContentType
instance uniquely identified by the given application label and modelname. The primary purpose of this method is to allowContentType
objects to bereferenced via a natural keyduring deserialization.
The get_for_model()
method is especiallyuseful when you know you need to work with aContentType
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>
Generic relations
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 thePermission
model above. But it's possibleto go one step further and useContentType
to enable trulygeneric (sometimes called "polymorphic") relationships between models.
A simple example is a tagging system, which might look like this:
- 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 ForeignKey
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
ForeignKey
toContentType
. 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
PositiveIntegerField
. 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 namesGenericForeignKey
willlook for. for_concrete_model
- If
False
, the field will be able to reference proxy models. DefaultisTrue
. This mirrors thefor_concrete_model
argument toget_for_model()
.
- Give your model a
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 eitherIntegerField
orCharField
primary key fields, youcan use CharField
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 aTextField
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 ContentType
objects. See natural keys anddumpdata —natural-foreign
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
:
- >>> 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>
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
Due to the way GenericForeignKey
is implemented, you cannot use such fields directly with filters (filter()
and exclude()
, for example) via the database API. Because aGenericForeignKey
isn't anormal 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, GenericForeignKey
sdoes not appear in ModelForm
s.
Reverse generic relations
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
:
- >>> 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 GenericRelation
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 doesGenericRelation
;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 aGenericRelation
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',
- )
Note also, that if you delete an object that has aGenericRelation
, any objectswhich have a GenericForeignKey
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
,GenericForeignKey
does not acceptan on_delete
argument to customize thisbehavior; if desired, you can avoid the cascade-deletion simply by not usingGenericRelation
, and alternatebehavior can be provided via the pre_delete
signal.
Generic relations and aggregation
Django's database aggregation API works with aGenericRelation
. For example, youcan find out how many tags all the bookmarks have:
- >>> Bookmark.objects.aggregate(Count('tags'))
- {'tags__count': 3}
Generic relation in forms
The django.contrib.contenttypes.forms
module provides:
BaseGenericInlineFormSet
- A formset factory,
generic_inlineformset_factory()
, for use withGenericForeignKey
. - 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
usingmodelformset_factory()
.
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()
andinlineformset_factory()
.
The for_concrete_model
argument corresponds to thefor_concrete_model
argument on GenericForeignKey
.
Generic relations in admin
The django.contrib.contenttypes.admin
module providesGenericTabularInline
andGenericStackedInline
(subclasses ofGenericInlineModelAdmin
)
These classes and functions enable the use of generic relations in formsand the admin. See the model formset andadmin documentation for moreinformation.
- class
GenericInlineModelAdmin
The
GenericInlineModelAdmin
class inherits all properties from anInlineModelAdmin
class. However,it adds a couple of its own for working with the generic relation:ct_field
The name of the
ContentType
foreign keyfield on the model. Defaults tocontent_type
.- The name of the integer field that represents the ID of the relatedobject. Defaults to
object_id
.
- class
GenericStackedInline
- Subclasses of
GenericInlineModelAdmin
with stacked and tabularlayouts, respectively.