many relationship for a model in Django admin (list mode)

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

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?


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'

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.

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

Greetings, Lukasz

链接地址: http://www.djcxy.com/p/60202.html

上一篇: Django ORM和工作单元

下一篇: Django admin中的模型的许多关系(列表模式)