Skip to content

Instantly share code, notes, and snippets.

@slykar
Last active December 21, 2023 01:26
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save slykar/c7dc5aa78813601e21426c27dae6ca8f to your computer and use it in GitHub Desktop.
Save slykar/c7dc5aa78813601e21426c27dae6ca8f to your computer and use it in GitHub Desktop.
Combining django-treebeard Materialized Path tree with django-model-utils InheritanceManager #django
from model_utils.managers import InheritanceManagerMixin, InheritanceQuerySetMixin
from treebeard.mp_tree import MP_NodeManager, MP_NodeQuerySet, MP_Node
class PolymorphicTreeQuerySet(InheritanceQuerySetMixin, MP_NodeQuerySet):
"""QuerySet combining functionality of polymorphic up-casting with Materialized Path tree structure"""
class PolymorphicTreeManager(InheritanceManagerMixin, MP_NodeManager):
_queryset_class = PolymorphicTreeQuerySet
def get_queryset(self):
return self._queryset_class(self.model).order_by('path')
class PolymorphicTreeNode(MP_Node):
"""
Base model for tree structures using Materialized Path approach.
"""
objects = PolymorphicTreeManager()
class Meta:
abstract = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment