user138016
user138016

Reputation:

Django self-referential relationship?

I'm trying to create model Page, page should be able to have "child pages" too.

My model code below keeps crashing Python 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 does this kinda HTML-rendering belong to views?

Thanks.

Upvotes: 8

Views: 8130

Answers (2)

meder omuraliev
meder omuraliev

Reputation: 186662

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?

Upvotes: 8

Jordan Reiter
Jordan Reiter

Reputation: 21022

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.

Upvotes: 14

Related Questions