使用するリレーション属性フィールドが多数あり、list_display
それぞれに対して関数 (およびその属性) を作成したくない場合は、汚れているが単純な解決策は、ModelAdmin
instace__getattr__
メソッドをオーバーライドして、その場で callable を作成することです。
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
として定義する必要があります。ModelAdmin
book__author_verbose_name = 'Author name'
category__is_new_boolean = True
callableadmin_order_field
属性は自動的に定義されます。
Django に追加のクエリを回避させるために、 list_select_related属性を使用することを忘れないでください。ModelAdmin