我有一个Person模型,它与Book有外键关系,Book有许多字段,但我最关心的是author(一个标准CharField)。
话虽如此,在我的PersonAdmin模型中,我想显示book。作者使用list_display:
class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
我已经尝试了所有显而易见的方法,但似乎都不起作用。
有什么建议吗?
我有一个Person模型,它与Book有外键关系,Book有许多字段,但我最关心的是author(一个标准CharField)。
话虽如此,在我的PersonAdmin模型中,我想显示book。作者使用list_display:
class PersonAdmin(admin.ModelAdmin):
list_display = ['book.author',]
我已经尝试了所有显而易见的方法,但似乎都不起作用。
有什么建议吗?
当前回答
我更喜欢这个:
class CoolAdmin(admin.ModelAdmin):
list_display = ('pk', 'submodel__field')
@staticmethod
def submodel__field(obj):
return obj.submodel.field
其他回答
这个答案已经被接受了,但如果还有其他傻瓜(比如我)没有立即从目前接受的答案中得到它,这里有更多的细节。
ForeignKey引用的模型类需要有一个__unicode__方法,如下所示:
class Category(models.Model):
name = models.CharField(max_length=50)
def __unicode__(self):
return self.name
这对我来说很重要,也适用于上述情况。这适用于Django 1.0.2。
如果你尝试在内联,你不会成功,除非:
在内联中:
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
你可以使用可调用对象在列表显示中显示你想要的任何东西。它看起来是这样的:
def book_author(object): return object.book.author class PersonAdmin(admin.ModelAdmin): list_display = [book_author,]
如果你有很多关系属性字段要在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
这里的要点是
可调用的特殊属性如boolean和short_description必须定义为ModelAdmin属性,例如book__author_verbose_name = '作者名'和category__is_new_boolean = True。
可调用的admin_order_field属性是自动定义的。
不要忘记在ModelAdmin中使用list_select_related属性,以使Django避免额外的查询。
在PyPI中有一个非常容易使用的包可以处理这个问题:django-related-admin。你也可以在GitHub中看到代码。
使用它,你想要达到的效果很简单:
class PersonAdmin(RelatedFieldAdmin):
list_display = ['book__author',]
这两个链接都包含了安装和使用的全部细节,所以我不会把它们粘贴在这里,以防它们发生变化。
顺便说一句,如果你已经在使用模型以外的东西。Admin(例如,我使用的是SimpleHistoryAdmin代替),你可以这样做:类MyAdmin(SimpleHistoryAdmin, RelatedFieldAdmin)。