简体   繁体   中英

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM