Adding generic relations to your models

In generic relations, ContentType objects play the role of pointing to the model used for the relationship. You will need three fields to set up a generic relation in a model:

  • A ForeignKey field to ContentType: This will tell us the model for the relationship
  • A field to store the primary key of the related object: This will usually be a PositiveIntegerField to match Django's automatic primary key fields
  • A field to define and manage the generic relation using the two previous fields: The content types framework offers a GenericForeignKey field for this purpose

Edit the models.py file of the actions application and make it look like this:

from django.db import modelsfrom django.contrib.contenttypes.models ...

Get Django 2 by Example 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.