开发者

Model with recursive self relation in Django's admin

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 obj开发者_如何学运维ect and later list them?

What I would like to have is this:

Model with recursive self relation in Django's admin

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,
    ]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜