在Django管理员(列表模式)中显示一个模型的一对多关系 [英] display one-to-many relationship for a model in Django admin (list mode)
问题描述
在Django管理站点中,列出给定模型的所有对象时,我知道我们可以通过 list_display
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
说明ModelA与ModelB有一对多的关系。我想在ModelA的列表页面上添加另一列,其中每个条目是指向ModelB的所有对象的URL,该对象具有与该行中的模型A的相应实例上的外键关系。如何使用管理员应用程序实现这种定制?
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的管理类添加一个方法:
you should add a method to ModelA's admin class:
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'
在url中,'modela__id__exact'部分是列表页面的过滤器,其中'modela'是外部键字段的名称,在ModelB类中,链接到ModelA。
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.
然后在list_display属性中使用此方法,并完成。如果您遇到任何问题,请问,我会尽力帮助。
Then use this method in 'list_display' property and you are done. If you encounter any problems, just ask, I'll try to help.
问候,
Lukasz
Greetings, Lukasz
这篇关于在Django管理员(列表模式)中显示一个模型的一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!