[Django]-Django-MPTT leaf nodes of multiple types

6đź‘Ť

âś…

AFAIK, this is not possible; django-mptt piggy backs on Django’s QuerySet, which will only ever work with one type of things. You can a use the contenttypes framework to associate the “real” item with something like FolderItem, which would only be used for the hierarchy, e.g.

from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic

class FolderItem(MPTTModel):
    folder = TreeForeignKey('Folder', related_name='folders', blank=True, null=True
    order = models.PositiveIntegerField()
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = generic.GenericForeignKey('content_type', 'object_id')

    class Meta:
        abstract = True

    class MPTTMeta:
        parent_attr = 'folder'
        order_insertion_by = ['order']

Then, when you’re using the django-mptt manager methods and such, you’ll get back a queryset of FolderItems, and you can access the Folder/Image for each as you iterate over the set, through the generic foreign key.

However, be aware that this will likely be costly in terms of database queries, since each time you access a generic foreign key, a new query must be issued.

👤Chris Pratt

Leave a comment