Can quot;list_displayquot; in a Django ModelAdmin display attributes of ForeignKey fields?(可以“list_display在 Django ModelAdmin 中显示 ForeignKey 字段的属性?)
问题描述
我有一个 Person 模型,它与 Book 有外键关系,它有许多字段,但我最关心的是 author(一个标准的 CharField).
I have a Person model that has a foreign key relationship to Book, which has a number of fields, but I'm most concerned about author (a standard CharField).
话虽如此,在我的 PersonAdmin 模型中,我想使用 list_display 显示 book.author:
With that being said, in my PersonAdmin model, I'd like to display book.author using list_display:
class PersonAdmin(admin.ModelAdmin):
    list_display = ['book.author',]
我已经尝试了所有明显的方法,但似乎没有任何效果.
I've tried all of the obvious methods for doing so, but nothing seems to work.
有什么建议吗?
推荐答案
作为另一种选择,您可以进行如下查找:
As another option, you can do look ups like:
class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')
    
    def get_author(self, obj):
        return obj.book.author
    get_author.short_description = 'Author'
    get_author.admin_order_field = 'book__author'
从 Django 3.2 开始,您可以使用 display() 装饰器:
Since Django 3.2 you can use display() decorator:
class UserAdmin(admin.ModelAdmin):
    list_display = (..., 'get_author')
    
    @display(ordering='book__author', description='Author')
    def get_author(self, obj):
        return obj.book.author
                        这篇关于可以“list_display"在 Django ModelAdmin 中显示 ForeignKey 字段的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以“list_display"在 Django ModelAdmin 中显示 ForeignKey 字段的属性?
				
        
 
            
        基础教程推荐
- 包装空间模型 2022-01-01
 - 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
 - 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
 - 修改列表中的数据帧不起作用 2022-01-01
 - 在Python中从Azure BLOB存储中读取文件 2022-01-01
 - 求两个直方图的卷积 2022-01-01
 - PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
 - PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
 - 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
 - Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
				
				
				
				