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. ContentTypealso 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 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 an 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 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_labelwill be set to 'sites' (the last part of the Pythonpath django.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 ContentTyperepresents, and doeson that model, returning the corresponding object.

    • ContentType.model_class()

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

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

      • getfor_model(_model, for_concrete_model=True)

      • Takes either a model class or an instance of a model, and returns the 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 the of proxymodels.

      • getby_natural_key(_app_label, model)

      • Returns the instance uniquely identified by the given application label and modelname. The primary purpose of this method is to allowContentType 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:

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

    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 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 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 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 names 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 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:

    1. >>> guido.delete()
    2. >>> t.content_object # returns None
    1. # This will fail
    2. >>> TaggedItem.objects.filter(content_object=guido)
    3. # This will also fail

    Likewise, sdoes not appear in ModelForms.

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

    Defining 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 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_deletesignal.

    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}

    The module provides:

    • BaseGenericInlineFormSet
    • A formset 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 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_modelargument 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 GenericInlineModelAdminclass inherits all properties from an class. However,it adds a couple of its own for working with the generic relation:

      • ct_field
      • The name of the 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