We will create a hierarchical Category model and tie it to the Idea model, which will have a many-to-many relationship with the categories, as follows:
- Open the models.py file in the categories app and add a Category model that extends mptt.models.MPTTModel and
CreationModificationDateBase, defined in Chapter 2, Models and 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:
# myproject/apps/ideas/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
from myproject.apps.core.models import CreationModificationDateBase
class Category(MPTTModel, CreationModificationDateBase):
parent = TreeForeignKey(
"self", on_delete=models.CASCADE,
blank=True, null=True, related_name="children"
)
title = models.CharField(_("Title"), max_length=200)
class Meta:
ordering = ["tree_id", "lft"]
verbose_name = _("Category")
verbose_name_plural = _("Categories")
class MPTTMeta:
order_insertion_by = ["title"]
def __str__(self):
return self.title
- Update the Idea model to include the categories field of the TreeManyToManyField type:
# myproject/apps/ideas/models.py
from django.utils.translation import gettext_lazy as _
from mptt.fields import TreeManyToManyField
from myproject.apps.core.models import CreationModificationDateBase, UrlBase
class Idea(CreationModificationDateBase, UrlBase):
# …
categories = TreeManyToManyField(
"categories.Category",
verbose_name=_("Categories"),
related_name="category_ideas",
)
- Update your database by making migrations and running them:
(env)$ python manage.py makemigrations
(env)$ python manage.py migrate