Django管理员中具有递归自我关系的模型 [英] Model with recursive self relation in Django's admin

查看:554
本文介绍了Django管理员中具有递归自我关系的模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个具有两个自递归关系的模型:

  class Article(Item):#Item是一个抽象类
date = models.DateField()
parent = models.OneToOneField('self',null = True,blank = True)
subatricles = models.ForeignKey('self' ,null = True,blank = True,related_name ='subs')

- 它可以有很多孩子(如果提供)和一个父母(如果有的话)。但是,当我在Django的管理员注册我的模型时,我的小儿子被显示为一对一 - 在这两种情况下,都有选择框,但是在后面的多个值不能被选择。



如何通过管理窗格将子项添加到此文章对象中,稍后列出?



我想要的是这样的:
而不是正常的下拉菜单。



解决方案

您只需要一个字段 parent 子粒子作为related_name提供反向查找:

  class Article(Item):#Item在这种情况下是一个抽象类
date = models.DateField()
parent = models.ForeignKey('self',null = True,blank = True,related_name ='subarticles')

所以如果你有一个文章对象,你想得到它的父母,请使用:

  article.pa租

如果你想得到孩子,你可以使用:

  article.subarticles 

在管理员界面来显示子粒子最简单的方法是使用 InlineModelAdmin

  class ArticleInline(admin.StackedInline):
model = article

class ArticleAdmin(admin.ModelAdmin):
inlines = [
ArticleInline,
]
/ pre>

Say we have a model with two self-recursive relations:

class Article(Item): # Item in this case is an abstract class
    date = models.DateField()
    parent = models.OneToOneField('self', null=True, blank=True)
    subatricles = models.ForeignKey('self', null=True, blank=True, related_name='subs')

Article acts here as a node - it can has many children (if supplied) and one parent (if any). However, when I register my model in Django's admin my subatricles are shown as "one-to-one' - in both cases there are choice boxes but in the latter multiple values cannot be selected, though.

How can I add children via the admin pane to this Article object and later list them?

What I would like to have is this: instead of normal drop-down.

Thanks.

解决方案

You only need one field parent with subarticles as related_name to provide the reverse lookup:

class Article(Item): # Item in this case is an abstract class
    date = models.DateField()
    parent = models.ForeignKey('self', null=True, blank=True, related_name='subarticles')

so if you have an article object and you want to get its parent, use:

article.parent

if you want to get its children, you use:

article.subarticles

In the admin interface to show the subarticles the easiest way is to use the InlineModelAdmin:

class ArticleInline(admin.StackedInline):
    model = Article

class ArticleAdmin(admin.ModelAdmin):
    inlines = [
        ArticleInline,
    ]

这篇关于Django管理员中具有递归自我关系的模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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