简体   繁体   English

Django自引用关系?

[英]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):我下面的模型代码在我的 Mac (python 2.6.1) 和 Ubuntu 10.04 (python 2.6.5) 上不断使Python 崩溃

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?或者这种 HTML 渲染属于视图吗?

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. HTML 呈现通常发生在视图中,而不是模型中。 Use mptt as meder suggests.按照 meder 的建议使用 mptt。

I suggest you use django-mptt which offers easier to use method of recursively spitting the structure out.我建议您使用django-mptt ,它提供了更易于使用的递归吐出结构的方法。

You have to register mptt with the model first , though.你必须注册与模型MPTT第一,虽然。

Here is my code using it: Including foreign key count in django mptt full tree listing?这是我使用它的代码: 在 django mptt 完整树列表中包含外键计数?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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