Ben
Ben

Reputation: 7124

How to set up a chain/tree of models with ForeignKeys

I have no idea if I phrased the question right. Feel free to comment if I should have called it something else.

But this is what I'm trying to accomplish, some hierarchy structure of models like so:

Page <--- SubPage.1 <--- SubPage.1.1 <--- SubPage.1.1.1 ...
  |__________|                 ^                           ...and so on
  |                            |-- SubPage.1.1.2 ...
  |                            
 tags #m2m or some other object
      #with foreign key relation 

Some other attributes:

  1. Subpage holds all the same information that Page has
  2. All foreign keys and m2m fields that point to Page also apply to SubPage
  3. I want to be able to access the parent subpage and the root Page quickly without too many db hits

so what is the best way to do this holding to the DRY philosophy?

This is what I have:

class Page(models.Model):
    ....

class SubPage(Page):
    parent = models.ForeignKey('self', related_name = 'subpage_set', blank = 'True')
    root = models.ForeignKey(Page, related_name = 'rootpage_set')

I don't like this way of doing it though for several reasons. 1) SubPage.root is repetitive, It's just there to quickly find Page. 2) Saving a SubPage object also saves a Page object, and I want to keep them separate.

I appreciate the help, Thanks

Upvotes: 0

Views: 340

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239440

Use django-mptt or django-treebeard. I personally prefer django-mptt, but they're both mature projects that handle relational hierarchy well.

Upvotes: 3

Related Questions