Creating a model mixin to handle generic relations

Besides normal database relationships such as a foreign-key relationship or many-to-many relationship, Django has a mechanism to relate a model to an instance of any other model. This concept is called generic relations. For each generic relation, there is a content type of the related model that is saved as well as the ID of the instance of this model.

In this recipe, we will see how to generalize the creation of generic relations in the model mixins.

Getting ready

For this recipe to work, you need to have the contenttypes app installed. It should be in the INSTALLED_APPS directory by default, as shown in the following:

# settings.py
INSTALLED_APPS = (
    # …
    "django.contrib.contenttypes",
)

Again, ...

Get Django: Web Development with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.