在django模型中建立树结构? [英] Making a tree structure in django models?
问题描述
从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屋!