在django模型中建立树结构? [英] Making a tree structure in django models?

查看:487
本文介绍了在django模型中建立树结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个有2个字段的模型,孩子和父母。在django中怎么做?我有这样的东西

 从django.db导入模型
class FooModel(models.Model)
parent = models.ForeignKey('self',blank = True,null = True)
children = models.ManyToOneRel('self',blank = True,null = True)

def __init__ (self,* args,** kwargs):
super(FooModel,self).__ init __(* args,** kwargs)
self.parent.children.add(self)

但我不认为我应该像这样使用ManyToOneRel(特别是因为它给我一个关键字错误'空白')。任何建议?

解决方案

ManyToOneRel 是一个内部实现类,它不是在您的模型中使用。



但是您为什么认为您需要它?正如文档详细解释的那样,当您定义一个ForeignKey时,您会自动获得反向关系。所以在你的情况下,如果你定义了 parent ,那么你自动得到 self.foomodel_set ,你甚至可以使它使用 related_name 参数更明确:

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

请注意如果你打算用树做复杂的事情,你可能想要使用django-mptt库。


I want to have a model with 2 fields, children and parent. How do I do this in django? I have something like this

from django.db import models
class FooModel(models.Model)
    parent = models.ForeignKey('self', blank=True, null=True)
    children = models.ManyToOneRel('self', blank=True, null=True)

    def __init__(self, *args, **kwargs):
        super(FooModel, self).__init__(*args, **kwargs)
        self.parent.children.add(self)

But I don't think i'm supposed to use the ManyToOneRel like this (especially because it's giving me a keyword error on 'blank'). Any advice?

解决方案

ManyToOneRel is an internal implementation class, it's not for use in your models.

But why do you think you need it anyway? As the documentation explains in detail, when you define a ForeignKey, you automatically get a reverse relation. So in your case, if you define parent then you automatically get self.foomodel_set already: and you can make it even more explicit by using the related_name parameter:

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

Note that if you're planning on doing complicated things with trees, you probably want to be using the django-mptt library.

这篇关于在django模型中建立树结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆