The contenttypes framework

    At the heart of the contenttypes application is the 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 are automatically created whenever new models are installed.

    Instances of ContentType have methods for returning the model classes they represent and for querying objects from those models. also has a custom manager that adds methods for working with and for obtaining instances of ContentType for a particular model.

    Relations between your models and can also be used to enable “generic” relationships between an instance of one of your models and instances of any model you have installed.

    The contenttypes framework is included in the default INSTALLED_APPS list created by django-admin startproject, but if you’ve removed it or if you manually set up your 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 framework installed; several of Django’s other bundled applications require it:

    • The admin application uses it to log the history of each object added or changed through the admin interface.
    • Django’s uses it to tie user permissions to specific models.

    class ContentType

    Each instance of has two fields which, taken together, uniquely describe an installed model:

    • app_label

      The name of the application the model is part of. This is taken from the attribute of the model, and includes only the last part of the application’s Python import path; django.contrib.contenttypes, for example, becomes an app_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 the attribute of the model.

    Let’s look at an example to see how this works. If you already have the contenttypes application installed, and then add to your INSTALLED_APPS setting and run manage.py migrate to install it, the model will be installed into your database. Along with it a new instance of ContentType will be created with the following values:

    • will be set to 'sites' (the last part of the Python path django.contrib.sites).
    • model will be set to 'site'.

    Each instance has methods that allow you to get from a ContentType instance to the model it represents, or to retrieve objects from that model:

    ContentType.``get_object_for_this_type(\*kwargs*)

    Takes a set of valid lookup arguments for the model the represents, and does a get() lookup on that model, returning the corresponding object.

    ContentType.``model_class()

    Returns the model class represented by this ContentType instance.

    For example, we could look up the for the User model:

    And then use it to query for a particular , or to get access to 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 enable two extremely important use cases:

    1. 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 app_label and model into a ContentType lookup at runtime, and then work with the model class or retrieve objects from it.
    2. You can relate another model to as 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. For example, the permissions system in Django’s authentication framework uses a model with a foreign key to ContentType; this lets represent concepts like “can add blog entry” or “can delete news story”.

    class ContentTypeManager

    also has a custom manager, ContentTypeManager, which adds the following methods:

    • clear_cache()

    • get_for_model(model, for_concrete_model=True)

      Takes either a model class or an instance of a model, and returns the instance representing that model. for_concrete_model=False allows fetching the ContentType of a proxy model.

    • get_for_models(\models, for_concrete_models=True*)

      Takes a variadic number of model classes, and returns a dictionary mapping the model classes to the ContentType instances representing them. for_concrete_models=False allows fetching the of proxy models.

    • get_by_natural_key(app_label, model)

      Returns the instance uniquely identified by the given application label and model name. The primary purpose of this method is to allow ContentType objects to be referenced via a during deserialization.

    The get_for_model() method is especially useful when you know you need to work with a but don’t want to go to the trouble of obtaining the model’s metadata to perform a manual lookup:

    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 to ContentType allows your model to effectively tie itself to another model class, as in the example of the model above. But it’s possible to go one step further and use ContentType to enable truly generic (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. class TaggedItem(models.Model):
    5. tag = models.SlugField()
    6. content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    7. object_id = models.PositiveIntegerField()
    8. content_object = GenericForeignKey('content_type', 'object_id')
    9. def __str__(self):
    10. return self.tag

    A normal 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 (GenericForeignKey) which works around this and allows the relationship to be with any model:

    class GenericForeignKey

    There are three parts to setting up a GenericForeignKey:

    1. Give your model a to ContentType. The usual name for this field is “content_type”.
    2. 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 . The usual name for this field is “object_id”.
    3. 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 will look for.
    • for_concrete_model

      If False, the field will be able to reference proxy models. Default is 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 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 get_db_prep_value() method.

    For example, if you want to allow generic relations to models with either or CharField primary key fields, you can use for the “object_id” field on your model since integers can be coerced to strings by get_db_prep_value().

    For maximum flexibility you can use a 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 ContentType objects

    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 identify related objects. See natural keys and for more information.

    This will enable an API similar to the one used for a normal ForeignKey; each 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 creating a TaggedItem:

    If the related object is deleted, the content_type and object_id fields remain set to their original values and the GenericForeignKey returns None:

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

    Due to the way is implemented, you cannot use such fields directly with filters (filter() and exclude(), for example) via the database API. Because a GenericForeignKey isn’t a normal field object, these examples will not work:

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

    Likewise, s does not appear in s.

    • related_query_name

      The relation on the related object back to this object doesn’t exist by default. Setting related_query_name creates a relation from the related object back to this one. This allows querying and filtering from the related object.

    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:

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

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

    Defining GenericRelation with related_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 Bookmark from 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>]>

    If you don’t add the related_query_name, you can do the same 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 accepts the names of the content-type and object-ID fields as arguments, so too does GenericRelation; 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 to it. For example, if the TaggedItem model referred to above used fields named content_type_fk and object_primary_key to create its generic foreign key, then a GenericRelation back to it would need to be defined like so:

    Note also, that if you delete an object that has a , any objects which have a GenericForeignKey pointing at it will be deleted as well. In the example above, this means that if a Bookmark object were deleted, any TaggedItem objects pointing at it would be deleted at the same time.

    Unlike , GenericForeignKey does not accept an argument to customize this behavior; if desired, you can avoid the cascade-deletion by not using GenericRelation, and alternate behavior can be provided via the signal.

    Django’s database aggregation API works with a . For example, you can find out how many tags all the bookmarks have:

    1. >>> Bookmark.objects.aggregate(Count('tags'))
    2. {'tags__count': 3}

    The django.contrib.contenttypes.forms module provides:

    class BaseGenericInlineFormSet

    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, validate_max=False, for_concrete_model=True, min_num=None, validate_min=False)

    Returns a GenericInlineFormSet using modelformset_factory().

    You must provide ct_field and fk_field if they are different from the defaults, content_type and object_id respectively. Other parameters are similar to those documented in and inlineformset_factory().

    The for_concrete_model argument corresponds to the argument on GenericForeignKey.

    The django.contrib.contenttypes.admin module provides and GenericStackedInline (subclasses of )

    These classes and functions enable the use of generic relations in forms and the admin. See the model formset and documentation for more information.

    class GenericInlineModelAdmin

    The class inherits all properties from an InlineModelAdmin class. However, it adds a couple of its own for working with the generic relation:

    • ct_field

      The name of the ContentType foreign key field on the model. Defaults to content_type.

    • ct_fk_field

      The name of the integer field that represents the ID of the related object. Defaults to object_id.

    class GenericTabularInline

    class GenericStackedInline