How to do it...

We will enhance the Category model using the Materialized Path algorithm, as follows:

  1. Open the models.py file and update the Category model to extend treebeard.mp_tree.MP_Node instead of the standard Django Model. It should also inherit from 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 title field:
# ideas/models.py
from django.urls import reverse, NoReverseMatch
from django.db import models
from django.utils.translation import ugettext_lazy as _
from treebeard.mp_tree import MP_Node

from utils.models import CreationModificationDateMixin, UrlMixin
from utils.fields import (MultilingualCharField,
MultilingualTextField)


class Category(MP_Node, CreationModificationDateMixin):
class Meta:
verbose_name = _("Idea Category")
verbose_name_plural = _("Idea Categories")

node_order_by = ["title",]

title = MultilingualCharField(_("Title"), max_length=200)

def __str__(self):
return self.title


# ...
  1. This will require an update to the database, so next we'll need to migrate the ideas app:
(myproject_env)$ python3 manage.py makemigrations ideas
(myproject_env)$ python3 manage.py migrate ideas
  1. With the use of abstract model inheritance, treebeard tree nodes can be related to other models using the standard relationships. As such, the Idea model can continue to have a simple ManyToManyField relation to Category:
# ideas/models.py
class Idea(UrlMixin):
# ...
categories = models.ManyToManyField(Category,
blank=True,
related_name="ideas",
verbose_name=_(
"Categories"))
# ...
..................Content has been hidden....................

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