Display foreign key columns as link to detail object in Django admin

后端 未结 3 739
小鲜肉
小鲜肉 2021-02-02 04:18

As explained in link-in-django-admin-to-foreign-key-object, one can display a ForeignKey field as a link to the admin detail page.

To summarize,

class Fo         


        
3条回答
  •  长发绾君心
    2021-02-02 04:49

    A good start would be looking at the source of BaseModelAdmin and ModelAdmin. Try to find out how the ModelAdmin generates the default links. Extend ModelAdmin, add a method to generate links to arbitrary foreign keys and look at how ChangeList generates the change list.

    I would also suggest you use format_html to render the links, which makes link_to_bar.allow_tags = True unnecessary:

    from django.utils.html import format_html
    
    class FooAdmin(ModelAdmin):
        list_display = ('link_to_bar', )
        def link_to_bar(self, obj):
            link = urlresolvers.reverse('admin:app_bar_change', args=[obj.bar_id])
            return format_html('{}', link, obj.bar) if obj.bar else None
    

提交回复
热议问题