Django自我参照关系? [英] Django self-referential relationship?
问题描述
我正在尝试创建模型页面,页面也应该有子页面。
我的模型代码保持崩溃Python 在我的Mac(python 2.6.1)和Ubuntu 10.04(python 2.6.5):
从django.db导入模型
/ pre>
从django.contrib import admin
类页面(models.Model):
slug = models $ s
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) b $ b html =< li>
html + = self.title
children = self.children.all()
如果len(children)> 0:
儿童页面:
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)
我做错了什么?还是这个HTML呈现属于视图?
谢谢。
解决方案我建议你使用
django-mptt
,它提供了更简单的递归分布结构的方法,例如@ http://django-mptt.github.com/django-mptt/templates.html
您必须使用型号注册mptt first ,但是。
这是我使用它的代码:在django中包含外键计数mptt全树列表?
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.
解决方案I suggest you use
django-mptt
which offers easier to use method of recursively spitting the structure out, example @ http://django-mptt.github.com/django-mptt/templates.htmlYou 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?
这篇关于Django自我参照关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!