1

I cannot seem to find a way to add nodes of various polymorphic types to the same tree. Basically, I think I want a tree whose nodes are either a Company or Region, both inheriting from HierarchyNode which inherits from MP_Node

class HierarchyNode(MP_Node):
    name = models.CharField(max_length=30)

class Company(HierarchyNode):
    pass

class Region(HierarchyNode):
    pass

Adding a Company root node is straight-forward

c1 = Company.add_root(name='Company 1')

But I can't seem to figure out how to add a Region as a child of c1

c1.add_child(name='Region 1') # adds a Company named Region 1
c1.add_child(Region(name='Region 1')) # isn't valid

Is there a way to do this? Does the API not allow this because it is a bad idea? Is there a more appropriate way to model this concept? Alternatively, I suppose I could have a tree of HierarchyNodes which have a one-to-one relationship to the Company/Region types.

James Maroney
  • 3,136
  • 3
  • 24
  • 27

1 Answers1

0

Ok, after looking through the code for django-treebeard, the way to do this is:

c1.add_child(instance=Region('Region 1'))

I am still not 100% sure this is a good idea, but this did at least persist the tree the way I was hoping it would.

James Maroney
  • 3,136
  • 3
  • 24
  • 27
  • see https://bitbucket.org/tabo/django-treebeard/src/af2a51c813cf13ff9aebc13d9908e9fbee1edbee/treebeard/mp_tree.py?at=default&fileviewer=file-view-default#mp_tree.py-336 – James Maroney Aug 12 '16 at 16:05