本文介绍了在Django管理员中,有没有一种方法可以显示实际链接到模型的一对多对象的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果这太复杂或不正确的做事方式,请随时将我链接到别的地方,或者只是告诉我我应该这样做...

If this is too complicated or not the right way to do things, feel free to link me to something else or just tell me I should do it another way...

基本上,我正在开发一个有客户端的项目,每个项目都附有任意数量的网站。所以网站模型有一个ForeignKey到客户端模型。网站管理员页面非常深入,每个客户端可能拥有10个或更多网站,所以我宁可不将其全部显示为内嵌,因为这真的很杂乱而且疯狂。

Basically, I'm working on a project where there are Clients, and each one has an arbitrary number of Websites attached to it. So the Websites model has a ForeignKey to the Client model. The Website admin page is pretty in-depth, and each Client might have 10 or more sites, so I'd rather not have them all display as inlines, because that's really messy and crazy looking.

我想要的是,当您进入管理面板并点击客户端时,您将被带到更改页面,其中包含您为客户端编辑的基本内容,然后是内联实际链接到每个客户的网站管理页面。像这样:

What I'd like is that when you go to the admin panel and click Clients, you're brought to the change page where it has the basic stuff you'd edit for the client and then an inline of actual links to each of the client's website admin pages. Like this:

名称:

地址:

电话:

链接到编辑网站1

链接到编辑网站2

链接到编辑网站3

链接到编辑网站4

链接到编辑网站5

推荐答案

您可以使用 TabularInline 链接到模型更改页面:

You can use a TabularInline that includes only a link to the model change page:

class ClientAdmin(admin.ModelAdmin):
    # everything as normal
    inlines = WebsiteInline,

class WebsiteInline(admin.TabularInline):
    model = Website
    fields = 'link',
    readonly_fields = 'link',
    def link(self, instance):
        url = reverse("admin:myapp_website_change", args = (instance.id,))
        return mark_safe("<a href='%s'>%s</a>" % (url, unicode(instance)))

admin.site.register(Client, ClientAdmin)
admin.site.register(Website)

查看我最近的问题如何将一个对象的Django管理页面中的链接添加到相关对象的管理页面? a>这是关于如何做到这一点,但与几对模型,而不只是一个。

See my recent question How do I add a link from the Django admin page of one object to the admin page of a related object? which was about how to do exactly this, but with several pairs of models rather than just one.

这篇关于在Django管理员中,有没有一种方法可以显示实际链接到模型的一对多对象的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!