Django self-referential relationship?

I am trying to create a model page, the page should also have "child pages".

My model code keeps Python crashing on my Mac (python 2.6.1) and Ubuntu 10.04 (python 2.6.5):

from django.db import models from django.contrib import admin class Page(models.Model): slug = models.SlugField(blank=True) title = models.CharField(max_length=100) content = models.TextField(blank=True) children = models.ManyToManyField("self", blank=True) published = models.BooleanField(default=True) created = models.DateTimeField(blank=True, auto_now_add=True) def html(self): html = "<li>" html += self.title children = self.children.all() if len(children) > 0: for page in children: html += page.html() html += "</li>" return html def __unicode__(self): return self.title class PageAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} admin.site.register(Page, PageAdmin) 

What am I doing wrong? Or is this kind of HTML rendering related to views?

Thanks.

+6
python django django-models
source share
2 answers

I suggest you use django-mptt , which offers an easier way to recursively splash a structure, e.g. @ http://django-mptt.github.com/django-mptt/templates.html

You need to register mptt with the model first.

Here is my code using it: Including the number of foreign keys in the django mptt full tree list?

+9
source share

In terms of the model itself, you just think about it in the wrong direction. Instead

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

using

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

This will allow you to directly access children directly from the page entry, but should be a simpler view in the database.

HTML rendering should usually be done in views, not in a model. Use mptt as a medium.

+13
source share

All Articles