views:

216

answers:

2

My application has two node types: a parent node which can hold recursive child nodes. Think of it like the post-comment system in SO, but comments can be recursive:

parent_1
  child_11
  child_12
    child_121
  child_13
parent_2
  child_21
    child_211
      child_2111

Important to note that the parent nodes have different attributes and behavior than the child nodes.

Barring recursion I would have the following models:

class Parent(models.Model):
    # fields ...

class Child(models.Model):
    parent = models.ForeignKey(Parent)
    # other fields ...

But the recursion complicates this. What is the correct (and presumably most efficient) way of modeling this relationship in Django?

+4  A: 

With django-mptt or django-treebeard.

Daniel Roseman
Daniel, can you please explain why I would need an external module to implement this rather simple model?
Yuval A
+1 for pointing me to django-treebeard. Nested Sets implementation = awesome timesaver for me.
celopes
@Yuval, it is a matter of efficiency of storing hierarchical data in a database. MPTT is one of the more common approaches in use today. Both of the projects that Daniel mentioned have more information on the subject as well as links to even more information. Here is one of the linked articles: http://articles.sitepoint.com/print/hierarchical-data-database
istruble
+1  A: 

Could you use a Generic Relation and just add validation in the save() method (or in a signal or form validation) to ensure the object is an instance of one or the other?

Tom