Adding ordering to module and content objects

Let's add the new field to our models. Edit the models.py file of the courses application, and import the OrderField class and a field to the Module model as follows:

from .fields import OrderFieldclass Module(models.Model):    # ...    order = OrderField(blank=True, for_fields=['course'])

We name the new field order, and we specify that the ordering is calculated with respect to the course by setting for_fields=['course']. This means that the order for a new module will be assigned adding 1 to the last module of the same Course object. Now, you can edit the __str__() method of the Module model to include its order as follows:

class Module(models.Model):    # ...    def __str__(self):        return '{}. {}'.format(self.order, ...

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.