Skip to main content
 首页 » 编程设计

python之django之需要从 list_display 引用另一个模型

2025年04月02日43jyk

当我点击作者字段时,我需要引用点击的作者模型管理员 - 如何做到这一点?

class BookAdmin(admin.ModelAdmin): 
     list_display = ['name', 'pub_date', 'author',] 

请您参考如下方法:

在管理类中

   def author_link(self, obj): 
        return '<a href="/admin/authors-appname/author-model-name/%s">%s</a>' \ 
               % (obj.auther.pk, obj.auther) 
    author_link.allow_tags = True 
    author_link.short_description = "auther" 
 
    list_display = ['name', 'pub_date', 'author_link',] 
    readonly_fields = ('author_link', ) 

更优雅的是更改模型中函数的硬链接(hard link) - get_auther_absolute_url 并从管理员调用它