<commit_before>.. _ref-contrib-contenttypes:

==========================
The contenttypes framework
==========================

.. module:: django.contrib.contenttypes
   :synopsis: Provides generic interface to installed models.

Django includes a :mod:`contenttypes` application that can track all of
the models installed in your Django-powered project, providing a
high-level, generic interface for working with your models.

Overview
========

At the heart of the contenttypes application is the
:class:`~django.contrib.contenttypes.models.ContentType` model, which lives at
``django.contrib.contenttypes.models.ContentType``. Instances of
:class:`~django.contrib.contenttypes.models.ContentType` represent and store
information about the models installed in your project, and new instances of
:class:`~django.contrib.contenttypes.models.ContentType` are automatically
created whenever new models are installed.

Instances of :class:`~django.contrib.contenttypes.models.ContentType` have
methods for returning the model classes they represent and for querying objects
from those models. :class:`~django.contrib.contenttypes.models.ContentType`
also has a :ref:`custom manager <custom-managers>` that adds methods for
working with :class:`~django.contrib.contenttypes.models.ContentType` and for
obtaining instances of :class:`~django.contrib.contenttypes.models.ContentType`
for a particular model.

Relations between your models and
:class:`~django.contrib.contenttypes.models.ContentType` can also be used to
enable "generic" relationships between an instance of one of your
models and instances of any model you have installed.

Installing the contenttypes framework
=====================================

The contenttypes framework is included in the default
:setting:`INSTALLED_APPS` list created by ``django-admin.py startproject``,
but if you've removed it or if you manually set up your
:setting:`INSTALLED_APPS` list, you can enable it by adding
``'django.contrib.contenttypes'`` to your :setting:`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 :mod:`authentication framework <django.contrib.auth>` uses it
      to tie user permissions to specific models.

    * Django's comments system (:mod:`django.contrib.comments`) uses it to
      "attach" comments to any installed model.

The ``ContentType`` model
=========================

.. class:: models.ContentType

    Each instance of :class:`~django.contrib.contenttypes.models.ContentType`
    has three fields which, taken together, uniquely describe an installed model:

    .. attribute:: models.ContentType.app_label

        The name of the application the model is part of. This is taken from
        the :attr:`app_label` attribute of the model, and includes only the *last*
        part of the application's Python import path;
        "django.contrib.contenttypes", for example, becomes an :attr:`app_label`
        of "contenttypes".

    .. attribute:: models.ContentType.model

        The name of the model class.

    .. attribute:: models.ContentType.name

        The human-readable name of the model. This is taken from the
        :attr:`verbose_name <django.db.models.fields.Field.verbose_name>`
        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
:mod:`the sites application <django.contrib.sites>` to your
:setting:`INSTALLED_APPS` setting and run ``manage.py syncdb`` to install it,
the model :class:`django.contrib.sites.models.Site` will be installed into
your database. Along with it a new instance of
:class:`~django.contrib.contenttypes.models.ContentType` will be
created with the following values:

    * :attr:`app_label` will be set to ``'sites'`` (the last part of the Python
      path "django.contrib.sites").

    * :attr:`model` will be set to ``'site'``.

    * :attr:`name` will be set to ``'site'``.

.. _the verbose_name attribute: ../model-api/#verbose_name

Methods on ``ContentType`` instances
====================================

.. class:: models.ContentType

    Each :class:`~django.contrib.contenttypes.models.ContentType` instance has
    methods that allow you to get from a
    :class:`~django.contrib.contenttypes.models.ContentType` instance to the model
    it represents, or to retrieve objects from that model:

.. method:: models.ContentType.get_object_for_this_type(**kwargs)

    Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the
    model the :class:`~django.contrib.contenttypes.models.ContentType`
    represents, and does :ref:`a get() lookup <get-kwargs>` on that model,
    returning the corresponding object.

.. method:: models.ContentType.model_class()

    Returns the model class represented by this
    :class:`~django.contrib.contenttypes.models.ContentType` instance.

For example, we could look up the
:class:`~django.contrib.contenttypes.models.ContentType` for the
:class:`~django.contrib.auth.models.User` 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 particular ``User``, or to get access
to 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,
:meth:`~django.contrib.contenttypes.models.ContentType.get_object_for_this_type`
and :meth:`~django.contrib.contenttypes.models.ContentType.model_class`
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 :class:`~django.contrib.contenttypes.models.ContentType`
       lookup at runtime, and then work with the model class or retrieve objects
       from it.

    2. You can relate another model to
       :class:`~django.contrib.contenttypes.models.ContentType` 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,
:class:`the permissions system <django.contrib.auth.models.Permission` in
Django's authentication framework uses a
:class:`~django.contrib.auth.models.Permission` model with a foreign
key to :class:`~django.contrib.contenttypes.models.ContentType`; this lets
:class:`~django.contrib.auth.models.Permission` represent concepts like
"can add blog entry" or "can delete news story".

The ``ContentTypeManager``
--------------------------

.. class:: models.ContentTypeManager

    :class:`~django.contrib.contenttypes.models.ContentType` also has a custom
    manager, :class:`~django.contrib.contenttypes.models.ContentTypeManager`,
    which adds the following methods:

    .. method:: models.ContentTypeManager.clear_cache()

        Clears an internal cache used by
        :class:`~django.contrib.contenttypes.models.ContentType>` to keep track
        of which models for which it has created
        :class:`django.contrib.contenttypes.models.ContentType>` instances. You
        probably won't ever need to call this method yourself; Django will call
        it automatically when it's needed.

    .. method:: models.ContentTypeManager.get_for_model(model)

        Takes either a model class or an instance of a model, and returns the
        :class:`~django.contrib.contenttypes.models.ContentType` instance
        representing that model.

The :meth:`~models.ContentTypeManager.get_for_model()` method is especially useful when you know you
need to work with a :class:`ContentType <django.contrib.contenttypes.models.ContentType>` but don't want to go to the
trouble of obtaining the model's metadata to perform a manual lookup::

    >>> from django.contrib.auth.models import User
    >>> user_type = ContentType.objects.get_for_model(User)
    >>> user_type<commit_msg>Fixed #11450 -- Corrected markup problem in contenttype docs. Thanks to seveas for the report.<commit_after>.. _ref-contrib-contenttypes:

==========================
The contenttypes framework
==========================

.. module:: django.contrib.contenttypes
   :synopsis: Provides generic interface to installed models.

Django includes a :mod:`contenttypes` application that can track all of
the models installed in your Django-powered project, providing a
high-level, generic interface for working with your models.

Overview
========

At the heart of the contenttypes application is the
:class:`~django.contrib.contenttypes.models.ContentType` model, which lives at
``django.contrib.contenttypes.models.ContentType``. Instances of
:class:`~django.contrib.contenttypes.models.ContentType` represent and store
information about the models installed in your project, and new instances of
:class:`~django.contrib.contenttypes.models.ContentType` are automatically
created whenever new models are installed.

Instances of :class:`~django.contrib.contenttypes.models.ContentType` have
methods for returning the model classes they represent and for querying objects
from those models. :class:`~django.contrib.contenttypes.models.ContentType`
also has a :ref:`custom manager <custom-managers>` that adds methods for
working with :class:`~django.contrib.contenttypes.models.ContentType` and for
obtaining instances of :class:`~django.contrib.contenttypes.models.ContentType`
for a particular model.

Relations between your models and
:class:`~django.contrib.contenttypes.models.ContentType` can also be used to
enable "generic" relationships between an instance of one of your
models and instances of any model you have installed.

Installing the contenttypes framework
=====================================

The contenttypes framework is included in the default
:setting:`INSTALLED_APPS` list created by ``django-admin.py startproject``,
but if you've removed it or if you manually set up your
:setting:`INSTALLED_APPS` list, you can enable it by adding
``'django.contrib.contenttypes'`` to your :setting:`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 :mod:`authentication framework <django.contrib.auth>` uses it
      to tie user permissions to specific models.

    * Django's comments system (:mod:`django.contrib.comments`) uses it to
      "attach" comments to any installed model.

The ``ContentType`` model
=========================

.. class:: models.ContentType

    Each instance of :class:`~django.contrib.contenttypes.models.ContentType`
    has three fields which, taken together, uniquely describe an installed model:

    .. attribute:: models.ContentType.app_label

        The name of the application the model is part of. This is taken from
        the :attr:`app_label` attribute of the model, and includes only the *last*
        part of the application's Python import path;
        "django.contrib.contenttypes", for example, becomes an :attr:`app_label`
        of "contenttypes".

    .. attribute:: models.ContentType.model

        The name of the model class.

    .. attribute:: models.ContentType.name

        The human-readable name of the model. This is taken from the
        :attr:`verbose_name <django.db.models.fields.Field.verbose_name>`
        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
:mod:`the sites application <django.contrib.sites>` to your
:setting:`INSTALLED_APPS` setting and run ``manage.py syncdb`` to install it,
the model :class:`django.contrib.sites.models.Site` will be installed into
your database. Along with it a new instance of
:class:`~django.contrib.contenttypes.models.ContentType` will be
created with the following values:

    * :attr:`app_label` will be set to ``'sites'`` (the last part of the Python
      path "django.contrib.sites").

    * :attr:`model` will be set to ``'site'``.

    * :attr:`name` will be set to ``'site'``.

.. _the verbose_name attribute: ../model-api/#verbose_name

Methods on ``ContentType`` instances
====================================

.. class:: models.ContentType

    Each :class:`~django.contrib.contenttypes.models.ContentType` instance has
    methods that allow you to get from a
    :class:`~django.contrib.contenttypes.models.ContentType` instance to the model
    it represents, or to retrieve objects from that model:

.. method:: models.ContentType.get_object_for_this_type(**kwargs)

    Takes a set of valid :ref:`lookup arguments <field-lookups-intro>` for the
    model the :class:`~django.contrib.contenttypes.models.ContentType`
    represents, and does :ref:`a get() lookup <get-kwargs>` on that model,
    returning the corresponding object.

.. method:: models.ContentType.model_class()

    Returns the model class represented by this
    :class:`~django.contrib.contenttypes.models.ContentType` instance.

For example, we could look up the
:class:`~django.contrib.contenttypes.models.ContentType` for the
:class:`~django.contrib.auth.models.User` 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 particular ``User``, or to get access
to 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,
:meth:`~django.contrib.contenttypes.models.ContentType.get_object_for_this_type`
and :meth:`~django.contrib.contenttypes.models.ContentType.model_class`
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 :class:`~django.contrib.contenttypes.models.ContentType`
       lookup at runtime, and then work with the model class or retrieve objects
       from it.

    2. You can relate another model to
       :class:`~django.contrib.contenttypes.models.ContentType` 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,
:class:`the permissions system <django.contrib.auth.models.Permission` in
Django's authentication framework uses a
:class:`~django.contrib.auth.models.Permission` model with a foreign
key to :class:`~django.contrib.contenttypes.models.ContentType`; this lets
:class:`~django.contrib.auth.models.Permission` represent concepts like
"can add blog entry" or "can delete news story".

The ``ContentTypeManager``
--------------------------

.. class:: models.ContentTypeManager

    :class:`~django.contrib.contenttypes.models.ContentType` also has a custom
    manager, :class:`~django.contrib.contenttypes.models.ContentTypeManager`,
    which adds the following methods:

    .. method:: models.ContentTypeManager.clear_cache()

        Clears an internal cache used by
        :class:`~django.contrib.contenttypes.models.ContentType` to keep track
        of which models for which it has created
        :class:`django.contrib.contenttypes.models.ContentType` instances. You
        probably won't ever need to call this method yourself; Django will call
        it automatically when it's needed.

    .. method:: models.ContentTypeManager.get_for_model(model)

        Takes either a model class or an instance of a model, and returns the
        :class:`~django.contrib.contenttypes.models.ContentType` instance
        representing that model.

The :meth:`~models.ContentTypeManager.get_for_model()` method is especially useful when you know you
need to work with a :class:`ContentType <django.contrib.contenttypes.models.ContentType>` but don't want to go to the
trouble of obtaining the model's metadata to perform a manual lookup::

    >>> from django.contrib.auth.models import User
    >>> user_type = ContentType.objects.get_for_model(User)
    >>> user_type
{'fraction_non_alphanumeric': 0.11046614938103418, 'fraction_numerical': 0.0005330806136350175, 'mean_word_length': 4.32114717932556, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 73, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '951756', 'n_tokens_mistral': 4468, 'n_tokens_neox': 4289, 'n_words': 1652}