Using the contenttypes framework

Django includes a contenttypes framework located at django.contrib.contenttypes. This application can track all models installed in your project and provides a generic interface to interact with your models.

The django.contrib.contenttypes application is included in the INSTALLED_APPS setting by default when you create a new project using the startproject command. It is used by other contrib packages, such as the authentication framework and the admin application.

The contenttypes application contains a ContentType model. Instances of this model represent the actual models of your application, and new instances of ContentType are automatically created when new models are installed in your project. The ContentType model has the following fields:

  • app_label: This indicates the name of the application the model belongs to. This is automatically taken from the app_label attribute of the model Meta options. For example, our Image model belongs to the images application.
  • model: The name of the model class.
  • name: This indicates the human-readable name of the model. This is automatically taken from the verbose_name attribute of the model Meta options.

Let's take a look at how we can interact with ContentType objects. Open the shell using the python manage.py shell command. You can obtain the ContentType object corresponding to a specific model by performing a query with the app_label and model attributes, as follows:

>>> from django.contrib.contenttypes.models import ContentType
>>> image_type = ContentType.objects.get(app_label='images', model='image')
>>> image_type
<ContentType: image>

You can also retrieve the model class from a ContentType object by calling its model_class() method:

>>> image_type.model_class()
<class 'images.models.Image'>

It's also common to get the ContentType object for a particular model class, as follows:

>>> from images.models import Image
>>> ContentType.objects.get_for_model(Image)
<ContentType: image>

These are just some examples of using content types. Django offers more ways to work with them. You can find the official documentation about the content types framework at https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset