How to do it...

We will create a hierarchical Category model and tie it to the Movie model, which will have a many-to-many relationship with the categories, as follows:

  1. Open the models.py file and add a Category model that extends mptt.models.MPTTModel and CreationModificationDateMixin, which we defined in  Chapter 2, Database Structure. In addition to the fields coming from the mixins, the Category model will need to have a parent field of the TreeForeignKey type and a title field:
# movies/models.py
from django.db import models
from django.utils.translation import ugettext_lazy as _
from mptt.models import MPTTModel
from mptt.fields import TreeForeignKey, TreeManyToManyField

from utils.models import CreationModificationDateMixin

RATING_CHOICES = (
# ...
)


class Category(MPTTModel, CreationModificationDateMixin):
class Meta:
ordering = ["tree_id", "lft"]
verbose_name = _("Category")
verbose_name_plural = _("Categories")

class MPTTMeta:
order_insertion_by = ["title"]


parent = TreeForeignKey("self",
on_delete=models.CASCADE,
blank=True,
null=True,
related_name="children")
title = models.CharField(_("Title"),
max_length=200)

# ...
  1. Update the Movie model to extend CreationModificationDateMixin. Also, make sure a title field is included and a categories field of the TreeManyToManyField type:
class Movie(models.Model):
# ...
categories = TreeManyToManyField(Category,
verbose_name=_("Categories"))
# ...
  1. Update your database by making migrations and running them for the movies app:
(myproject_env)$ python3 manage.py makemigrations movies
(myproject_env)$ python3 manage.py migrate movies
..................Content has been hidden....................

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