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, Models and Database Structure. In addition to the fields coming from the mixins, the Category model will need to have a title field:
# myproject/apps/categories/models.py
from
django.db import models
from django.utils.translation import ugettext_lazy as _
from treebeard.mp_tree import MP_Node

from myproject.apps.core.models import CreationModificationDateBase


class Category(MP_Node, CreationModificationDateBase):
title = models.CharField(_("Title"), max_length=200)

class Meta:
verbose_name = _("Category")
verbose_name_plural = _("Categories")

def __str__(self):
return self.title
  1. This will require an update to the database, so next, we'll need to migrate the categories app:
(env)$ python manage.py makemigrations
(env)$ python manage.py migrate
  1. With the use of abstract model inheritance, treebeard tree nodes can be related to other models using standard relationships. As such, the Idea model can continue to have a simple ManyToManyField relation to Category:
# myproject/apps/ideas/models.py
from django.db import models
from django.utils.translation import gettext_lazy as _

from myproject.apps.core.models import CreationModificationDateBase, UrlBase


class Idea(CreationModificationDateBase, UrlBase):
# …
categories = models.ManyToManyField(
"categories.Category",
verbose_name=_("Categories"),
related_name="category_ideas",
)
..................Content has been hidden....................

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