Se hai molti campi di attributi di relazione da usare list_displaye non vuoi creare una funzione (ed i suoi attributi) per ognuno, una soluzione sporca ma semplice avrebbe la ModelAdminprecedenza sul __getattr__metodo Instace , creando al volo i 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
Come qui
Attributi speciali richiamabili come booleane short_descriptiondevono essere definiti come ModelAdminattributi, ad es. book__author_verbose_name = 'Author name'Ecategory__is_new_boolean = True .
L' admin_order_fieldattributo richiamabile viene definito automaticamente.
Non dimenticare di utilizzare l' attributo list_select_related nel tuo ModelAdminper evitare che Django richieda query adizionali.
get_author, dal momento che è quello a cui effettivamente fa riferimento la stringa (e la breve descrizione)? O modificare l'argomento formato stringa inobj.book.reviews?