Django ModelAdmin中的"list_display"能展示ForeignKey字段的属性吗?

415

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

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

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

我已经尝试了所有显而易见的方法,但似乎没有什么作用。

有什么建议吗?

15个回答

6

我可能来晚了,但这是另一种方法。你可以在模型中定义一个方法并通过下面的list_display访问它:

models.py

class Person(models.Model):
    book = models.ForeignKey(Book, on_delete=models.CASCADE)

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

admin.py

class PersonAdmin(admin.ModelAdmin):
    list_display = ('get_book_author',)

但是这种方法以及上面提到的其他方法在你的列表视图页面中每行都会添加两个额外的查询。为了优化这一点,我们可以覆盖get_queryset来注释所需的字段,然后在我们的ModelAdmin方法中使用注释字段。

admin.py

from django.db.models.expressions import F

@admin.register(models.Person)
class PersonAdmin(admin.ModelAdmin):
    list_display = ('get_author',)
    def get_queryset(self, request):
        queryset = super().get_queryset(request)
        queryset = queryset.annotate(
            _author = F('book__author')
        )
        return queryset

    @admin.display(ordering='_author', description='Author')
    def get_author(self, obj):
        return obj._author

6
如果您有很多关系属性字段要在list_display中使用,但又不想为每个字段创建一个函数(及其属性),那么一种简单的但不太规范的解决方法是覆盖ModelAdmin实例的__getattr__方法,在运行时动态创建可调用对象:
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

作为此处所述,可调用的特殊属性(如booleanshort_description)必须作为ModelAdmin属性定义,例如:book__author_verbose_name = '作者姓名'category__is_new_boolean = True
可调用的admin_order_field属性是自动定义的。
不要忘记在ModelAdmin中使用list_select_related属性,以使Django避免额外的查询。

1
我刚尝试了在 Django 2.2 安装中使用此方法,相比其他方法,它对我非常有效。请注意,现在您需要从 functools 或其他地方导入 reduce... - Paul Brackin

4

如果您尝试在内联中使用它,除非:

您的内联中:

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

-1
AlexRobbins的回答对我有用,除了前两行需要在模型中(也许这是默认的?),并且应该引用self:
def book_author(self):
  return self.book.author

然后管理员部分工作得很好。


-5

我更喜欢这个:

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

    @staticmethod
    def submodel__field(obj):
        return obj.submodel.field

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接