Django self-referential relationship?

In terms of the model itself you're just thinking of this in the wrong direction. Instead of

children = models.ManyToManyField("self", blank=True)

use

parent = models.ForeignKey("self", blank=True, related_name="children")

This will let you access the children directly from a page record but should be a more straightforward representation in the database.

HTML rendering should generally happen in views, not in the model. Use mptt as meder suggests.


I suggest you use django-mptt which offers easier to use method of recursively spitting the structure out.

You have to register mptt with the model first, though.

Here is my code using it: Including foreign key count in django mptt full tree listing?