Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

django - Change list link to foreign key change page

When viewing the admin change list for a model, is it possible to make the columns that correspond to foreign keys links to their respective pages? A simple example is I have a Foo object which contains Bar as a foreign key. If I'm viewing the admin change list for Foo (and have it set to include Bar in the display_list columns), the main column would link to the Foo instance's edit page while the Bar column would link to the Boo instance's edit page. I understand I can override the template that's used, but I was curious if there was a solution that didn't require that.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can define a custom method to use in the changelist which returns the HTML of the link.

from django.core.urlresolvers import reverse

class MyFooAdmin(admin.ModelAdmin):
    list_display = ('foo', 'bar_link')

    def bar_link(self, obj):
        url = reverse('admin:myapp_bar_change', args=(obj.pk,))
        return '<a href="%s">Edit Bar</a>' % url 
    bar_link.allow_tags = True 

One problem with your question as stated - if Foo has a foreign key to Bar, then each foo links to a single bar, so you can link to the edit page for that bar. However, each bar links to multiple foos, so it doesn't make sense to ask for a link to 'the Foo instance's edit page'. What you can do is link to the changelist page for Foo with the filter set to only show the instances that link to this Bar:

    def foo_link(self, obj):
        url = reverse('admin:myapp_foo_changelist')
        return '<a href="%s?bar=%s">See Foos</a>' % (url, obj.pk) 
    foo_link.allow_tags = True 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...