在Django admin(列表模式)中显示模型的一对多关系

时间:2021-08-26 20:06:37

In Django admin site, when listing all the objects for a given model, I know we can customize which columns get displayed for a ModelA via list_display

在Django管理站点中,当列出给定模型的所有对象时,我知道我们可以通过list_display自定义为ModelA显示哪些列

Say that ModelA has a one-to-many relationship with ModelB. I would like to add another column on the listing page for ModelA, where each entry is a URL pointing to all objects of ModelB having a foreign key relationship on corresponding instance of Model A in that row. How can I achieve this customization with the admin app?

假设ModelA与ModelB有一对多的关系。我想在ModelA的列表页面上添加另一个列,其中每个条目都是指向ModelB的所有对象的URL,该对象在该行中对应的Model A实例上具有外键关系。如何使用管理员应用程序实现此自定义?

1 个解决方案

#1


1  

you should add a method to ModelA's admin class:

你应该为ModelA的管理类添加一个方法:

def modelb_link(self, inst):
    url = u'../modelb/?modela__id__exact=%d' % inst.id
    return u'<a href="%s">Models B</a>' % url
modelb_link.allow_tags = True
modelb_link.short_description = u'Models B'

In the url the 'modela__id__exact' part is a filter for list page, where 'modela' is the name of ForeignKey field, in ModelB class, that links to ModelA.

在url中,'modela__id__exact'部分是列表页面的过滤器,其中'modela'是在ModelB类中链接到ModelA的ForeignKey字段的名称。

Then use this method in 'list_display' property and you are done. If you encounter any problems, just ask, I'll try to help.

然后在'list_display'属性中使用此方法,您就完成了。如果您遇到任何问题,请问,我会尽力帮忙。

Greetings, Lukasz

问候,卢卡斯

#1


1  

you should add a method to ModelA's admin class:

你应该为ModelA的管理类添加一个方法:

def modelb_link(self, inst):
    url = u'../modelb/?modela__id__exact=%d' % inst.id
    return u'<a href="%s">Models B</a>' % url
modelb_link.allow_tags = True
modelb_link.short_description = u'Models B'

In the url the 'modela__id__exact' part is a filter for list page, where 'modela' is the name of ForeignKey field, in ModelB class, that links to ModelA.

在url中,'modela__id__exact'部分是列表页面的过滤器,其中'modela'是在ModelB类中链接到ModelA的ForeignKey字段的名称。

Then use this method in 'list_display' property and you are done. If you encounter any problems, just ask, I'll try to help.

然后在'list_display'属性中使用此方法,您就完成了。如果您遇到任何问题,请问,我会尽力帮忙。

Greetings, Lukasz

问候,卢卡斯