可以“列表显示”在Django ModelAdmin中显示ForeignKey字段的属性? [英] Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

查看:2512
本文介绍了可以“列表显示”在Django ModelAdmin中显示ForeignKey字段的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与书有外键关系的人物模型。书有很多领域,但我最关心的是作者(标准的CharField)。

I have a Person model that has a foreign key relationship to Book. Book has a number of fields, but I'm most concerned about "author" (a standard CharField).

据说,在我的PersonAdmin模型中, d喜欢使用list_display显示book.author。我已经尝试了所有这些明显的方法(见下文),但似乎没有任何效果。任何建议?

With that being said, in my PersonAdmin model, I'd like to display "book.author" using "list_display". I've tried all of the obvious methods for doing so (see below), but nothing seems to work. Any suggestions?

class PersonAdmin(admin.ModelAdmin):
  list_display = ['book.author',]


推荐答案

作为另一个选择,你可以做一些查找: / p>

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 ModelAdmin中显示ForeignKey字段的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆