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. ContentTypealso has a custom manager that adds methods forworking with ContentType and forobtaining instances of ContentTypefor 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 ContentTypehas 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 anapp_label of contenttypes.

    • model

    • 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 theverbose_nameattribute 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_labelwill be set to 'sites' (the last part of the Pythonpath django.contrib.sites).
  • modelwill 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 ContentTyperepresents, and doesa get() lookupon that model, returning the corresponding object.

  • ContentType.model_class()

  • Returns the model class represented by thisContentType instance.

For example, we could look up theContentType for theUser model:

  1. >>> from django.contrib.contenttypes.models import ContentType
  2. >>> user_type = ContentType.objects.get(app_label='auth', model='user')
  3. >>> user_type
  4. <ContentType: user>

And then use it to query for a particularUser, or to get accessto the User model class:

  1. >>> user_type.model_class()
  2. <class 'django.contrib.auth.models.User'>
  3. >>> user_type.get_object_for_this_type(username='Guido')
  4. <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 toContentType 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 to ContentType; 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 byContentType 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.

    • getfor_id(_id)

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

    • getfor_model(_model, for_concrete_model=True)

    • Takes either a model class or an instance of a model, and returns theContentType instancerepresenting that model. for_concrete_model=False allows fetchingthe ContentType 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 theContentType instancesrepresenting them. for_concrete_models=False allows fetching theContentType of proxymodels.

    • getby_natural_key(_app_label, model)

    • Returns the ContentTypeinstance 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:

  1. >>> from django.contrib.auth.models import User
  2. >>> ContentType.objects.get_for_model(User)
  3. <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:

  1. from django.contrib.contenttypes.fields import GenericForeignKey
  2. from django.contrib.contenttypes.models import ContentType
  3. from django.db import models
  4.  
  5. class TaggedItem(models.Model):
  6. tag = models.SlugField()
  7. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
  8. object_id = models.PositiveIntegerField()
  9. content_object = GenericForeignKey('content_type', 'object_id')
  10.  
  11. def __str__(self):
  12. 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 aGenericForeignKey:

    • Give your model a ForeignKeyto 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 aPositiveIntegerField. The usual namefor this field is "object_id".
    • Give your model aGenericForeignKey, 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. Defaultis True. This mirrors the for_concrete_model argument toget_for_model().

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 ContentTypeobjects. 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:

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

If the related object is deleted, the content_type and object_id fieldsremain set to their original values and the GenericForeignKey returnsNone:

  1. >>> guido.delete()
  2. >>> t.content_object # returns None

Due to the way GenericForeignKeyis 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:

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

Likewise, GenericForeignKeysdoes not appear in ModelForms.

Reverse generic relations

  • class GenericRelation
    • related_query_name
    • The relation on the related object back to this object doesn't exist bydefault. Setting related_query_name creates a relation from therelated object back to this one. This allows querying and filteringfrom the related object.

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:

  1. from django.contrib.contenttypes.fields import GenericRelation
  2. from django.db import models
  3.  
  4. class Bookmark(models.Model):
  5. url = models.URLField()
  6. tags = GenericRelation(TaggedItem)

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

  1. >>> b = Bookmark(url='https://www.djangoproject.com/')
  2. >>> b.save()
  3. >>> t1 = TaggedItem(content_object=b, tag='django')
  4. >>> t1.save()
  5. >>> t2 = TaggedItem(content_object=b, tag='python')
  6. >>> t2.save()
  7. >>> b.tags.all()
  8. <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>

Defining GenericRelation withrelated_query_name set allows querying from the related object:

  1. tags = GenericRelation(TaggedItem, related_query_name='bookmark')

This enables filtering, ordering, and other query operations on Bookmarkfrom TaggedItem:

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

Of course, if you don't add the related_query_name, you can do thesame types of lookups manually:

  1. >>> bookmarks = Bookmark.objects.filter(url__contains='django')
  2. >>> bookmark_type = ContentType.objects.get_for_model(Bookmark)
  3. >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id, object_id__in=bookmarks)
  4. <QuerySet [<TaggedItem: django>, <TaggedItem: python>]>

Just as GenericForeignKeyaccepts 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:

  1. tags = GenericRelation(
  2. TaggedItem,
  3. content_type_field='content_type_fk',
  4. object_id_field='object_primary_key',
  5. )

Note also, that if you delete an object that has aGenericRelation, any objectswhich have a GenericForeignKeypointing 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_deletesignal.

Generic relations and aggregation

Django's database aggregation API works with aGenericRelation. For example, youcan find out how many tags all the bookmarks have:

  1. >>> Bookmark.objects.aggregate(Count('tags'))
  2. {'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_modelargument 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 GenericInlineModelAdminclass 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 theContentType foreign keyfield on the model. Defaults to content_type.

    • ct_fk_field

    • The name of the integer field that represents the ID of the relatedobject. Defaults to object_id.
  • class GenericTabularInline

  • class GenericStackedInline
  • Subclasses of GenericInlineModelAdmin with stacked and tabularlayouts, respectively.