Django ModelAdmin中的“list_display”可以显示ForeignKey字段的属性吗?

时间:2008-10-02 18:26:20

标签: python django django-models django-admin modeladmin

我有一个Person模型,它与Book有一个外键关系,它有很多字段,但我最关心的是author(一个标准的CharField)。

话虽如此,在我的PersonAdmin模型中,我想使用book.author显示list_display

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

我已经尝试了所有明显的方法,但似乎没有任何效果。

有什么建议吗?

14 个答案:

答案 0 :(得分:409)

作为另一种选择,您可以进行如下搜索:

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'

答案 1 :(得分:112)

尽管上面有很多好的答案,并且由于我是Django的新手,但我还是被困住了。这是我从一个非常新手的角度来解释的。

<强> models.py

class Author(models.Model):
    name = models.CharField(max_length=255)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=255)

admin.py(错误的方式) - 您认为通过使用'model__field'来引用它会起作用,但它不会

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'author__name', ]

admin.site.register(Book, BookAdmin)

admin.py(正确方式) - 这就是你如何引用Django方式的外键名称

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'get_name', ]

    def get_name(self, obj):
        return obj.author.name
    get_name.admin_order_field  = 'author'  #Allows column order sorting
    get_name.short_description = 'Author Name'  #Renames column head

    #Filtering on side - for some reason, this works
    #list_filter = ['title', 'author__name']

admin.site.register(Book, BookAdmin)

有关其他参考,请参阅Django模型链接here

答案 2 :(得分:60)

和其他人一样,我也选择了咔嗒声。但他们有一个缺点:默认情况下,你不能订购它们。幸运的是,有一个解决方案:

def author(self):
    return self.book.author
author.admin_order_field  = 'book__author'

答案 3 :(得分:31)

请注意,添加get_author功能会降低管理员中的list_display速度,因为显示每个人都会进行SQL查询。

为避免这种情况,您需要在PersonAdmin中修改get_queryset方法,例如:

def get_queryset(self, request):
    return super(PersonAdmin,self).get_queryset(request).select_related('book')
  

之前:36.02毫秒中的73个查询(管理员中有67个重复查询)

     

之后:10.81ms内的6次查询

答案 4 :(得分:20)

根据文档,您只能显示ForeignKey的__unicode__表示形式:

http://docs.djangoproject.com/en/dev/ref/contrib/admin/#list-display

奇怪的是,它不支持在{...}数据库API中使用的'book__author'样式格式。

原来是a ticket for this feature,标记为无法修复。

答案 5 :(得分:10)

您可以使用callable在列表显示中显示您想要的任何内容。它看起来像这样:


def book_author(object):
  return object.book.author

class PersonAdmin(admin.ModelAdmin):
  list_display = [book_author,]

答案 6 :(得分:10)

我刚刚发布了一个代码片段,使admin.ModelAdmin支持'__'语法:

http://djangosnippets.org/snippets/2887/

所以你可以这样做:

class PersonAdmin(RelatedFieldAdmin):
    list_display = ['book__author',]

这基本上只是做其他答案中描述的相同的事情,但它会自动处理(1)设置admin_order_field(2)设置short_description和(3)修改查询集以避免每行的数据库命中。 / p>

答案 7 :(得分:6)

这个已被接受,但是如果还有其他假人(像我一样)没有立即从presently accepted answer获得,那么这里有更多细节。

ForeignKey引用的模型类需要在其中包含__unicode__方法,如下所示:

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __unicode__(self):
        return self.name

这对我有所帮助,应该适用于上述情况。这适用于Django 1.0.2。

答案 8 :(得分:4)

如果你在Inline中尝试,除非:

,否则你不会成功 你的内联中的

class AddInline(admin.TabularInline):
    readonly_fields = ['localname',]
    model = MyModel
    fields = ('localname',)
模型中的

(MyModel):

class MyModel(models.Model):
    localization = models.ForeignKey(Localizations)

    def localname(self):
        return self.localization.name

答案 9 :(得分:4)

如果在list_display中有很多关系属性字段,并且不想为每个属性字段创建一个函数(以及它的属性),那么一个简单但简单的解决方案将覆盖{ {1}} instace ModelAdmin方法,即时创建callables:

__getattr__

作为gist here

class DynamicLookupMixin(object): ''' a mixin to add dynamic callable attributes like 'book__author' which return a function that return the instance.book.author value ''' def __getattr__(self, attr): if ('__' in attr and not attr.startswith('_') and not attr.endswith('_boolean') and not attr.endswith('_short_description')): def dyn_lookup(instance): # traverse all __ lookups return reduce(lambda parent, child: getattr(parent, child), attr.split('__'), instance) # get admin_order_field, boolean and short_description dyn_lookup.admin_order_field = attr dyn_lookup.boolean = getattr(self, '{}_boolean'.format(attr), False) dyn_lookup.short_description = getattr( self, '{}_short_description'.format(attr), attr.replace('_', ' ').capitalize()) return dyn_lookup # not dynamic lookup, default behaviour return self.__getattribute__(attr) # use examples @admin.register(models.Person) class PersonAdmin(admin.ModelAdmin, DynamicLookupMixin): list_display = ['book__author', 'book__publisher__name', 'book__publisher__country'] # custom short description book__publisher__country_short_description = 'Publisher Country' @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin, DynamicLookupMixin): list_display = ('name', 'category__is_new') # to show as boolean field category__is_new_boolean = True boolean等可调用的特殊属性必须定义为short_description属性,例如ModelAdminbook__author_verbose_name = 'Author name'

可自动定义可调用category__is_new_boolean = True属性。

不要忘记使用admin_order_field中的list_select_related属性来让Django避免附加查询。

答案 10 :(得分:3)

PyPI中有一个非常容易使用的包,它可以处理:django-related-admin。您还可以see the code in GitHub

使用此功能,您想要实现的目标非常简单:

class PersonAdmin(RelatedFieldAdmin):
    list_display = ['book__author',]

这两个链接都包含安装和使用的完整详细信息,因此我不会将它们粘贴到此处,以防它们发生变化。

作为附注,如果您已经使用model.Admin以外的其他内容(例如我使用的是SimpleHistoryAdmin),您可以执行此操作:class MyAdmin(SimpleHistoryAdmin, RelatedFieldAdmin)。< / p>

答案 11 :(得分:3)

对于 Django >= 3.2

使用 Django 3.2 或更高版本执行此操作的正确方法是使用 display decorator

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'get_author_name']

    @admin.display(description='Author Name', ordering='author__name')
    def get_author_name(self, obj):
        return obj.author.name

答案 12 :(得分:-1)

AlexRobbins的回答对我有用,除了前两行需要在模型中(也许这是假设的?),并且应该引用自我:

def book_author(self):
  return self.book.author

然后管理部分很好用。

答案 13 :(得分:-4)

我更喜欢这个:

class CoolAdmin(admin.ModelAdmin):
    list_display = ('pk', 'submodel__field')

    @staticmethod
    def submodel__field(obj):
        return obj.submodel.field
相关问题