Creating models for diverse content

We plan to add different types of content to the course modules such as texts, images, files, and videos. We need a versatile data model that allows us to store diverse content. In Chapter 6, Tracking User Actions, you have learned the convenience of using generic relations to create foreign keys that can point to objects of any model. We are going to create a Content model that represents the modules' contents and define a generic relation to associate any kind of content.

Edit the models.py file of the courses application and add the following imports:

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey

Then, add the following code to the end of the file:

class Content(models.Model):
module = models.ForeignKey(Module,
related_name='contents',
on_delete=models.CASCADE)
content_type = models.ForeignKey(ContentType,
on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
item = GenericForeignKey('content_type', 'object_id')

This is the Content model. A module contains multiple contents, so we define a ForeignKey field to the Module model. We also set up a generic relation to associate objects from different models that represent different types of content. Remember that we need three different fields to set up a generic relationship. In our Content model, these are:

  • content_type: A ForeignKey field to the ContentType model
  • object_id: This is PositiveIntegerField to store the primary key of the related object
  • item: A GenericForeignKey field to the related object by combining the two previous fields

Only the content_type and object_id fields have a corresponding column in the database table of this model. The item field allows you to retrieve or set the related object directly, and its functionality is built on top of the other two fields.

We are going to use a different model for each type of content. Our content models will have some common fields, but they will differ in the actual data they can store.

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

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