[英]Django one-to-many relationship on single model
我正在尝试使用部分的Django模型。 每个部分可以有一个超级节,也可以没有超级节,每个部分可以有许多子节。 这是我的模特
class Section(models.Model):
section_name = models.CharField(max_length=100)
sub_sections = models.ForeignKey('self', related_name='super_section', null=True)
links = models.ForeignKey('Link')
def __str__(self):
return self.section_name
class Link(models.Model):
link_adress = models.URLField(max_length=2083)
link_text = models.CharField(max_length=50)
link_description = models.CharField
def __str__(self):
return self.link_text
这里的问题是试图让管理面板以我想要的方式工作。 在管理面板中,我希望能够查看和编辑子部分,并且(这里是我的问题)希望能够编辑当前部分所在的超级部分。
您的ModelClass
Section
是错误的。 现在, Section
对象只能有一个子部分。 您应该使用以下sub_sections
替换sub_sections
属性:
super_section = models.ForeignKey('self', related_name='sub_sections', null=True)
这样, Section
对象可以具有许多子节,但最多具有一个超级节。
有关ForeignKey
如何在Django中工作的更多信息,请参阅docs 。
现在到管理部分:
你可以修改你的管理面板来显示相关的对象(即超段和子段) Section
对象作为内联( TabularInline
或StackedInline
)。 请查看文档 ,以获取有关Django中可用的Inline
类的更多信息。
内联示例代码:
from django.contrib import admin
from yourapp.models import Section
class SectionInline(admin.TabularInline):
model = Section
class SectionAdmin(admin.ModelAdmin):
inlines = [
SectionInline,
]
您的模型有误。 如果我理解正确,这就是您想要的:
Super-section
|
Section
______|______
| | |
Sub Sub Sub
您的模型应如下所示:
class SuperSection(models.Model):
# define your fields here
# it doesn't need to have a ``ForeignKey``
class Section(...):
super_section = models.ForeignKey(SuperSection)
# define other fields
# doesn't need any more ``ForeignKey``
class SubSection(...):
section = models.ForeignKey(Section)
# define other keys
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.