以下是我的模特:
class Location(models.Model):
location_id = models.AutoField(primary_key=True)
location = models.CharField(max_length=30, blank=False, null=False)
class Host(models.Model):
host_id = models.AutoField(primary_key=True)
location = models.ForeignKey('Location', on_delete=models.PROTECT)
host = models.CharField(max_length=30, blank=False, null=False)
class Device(models.Model):
device_id = models.AutoField(primary_key=True)
host = models.ForeignKey('Host', on_delete=models.PROTECT)
model = models.ForeignKey('Model', on_delete=models.PROTECT)
ip = models.GenericIPAddressField(null=True)
name = models.CharField(max_length=30, blank=False, null=False)
这是DeviceAdmin
类:
class DeviceAdmin(admin.ModelAdmin):
list_display=('host','name','model', 'ip')
list_filter=(
('model', admin.RelatedOnlyFieldListFilter),
('host', admin.RelatedOnlyFieldListFilter),
)
admin.site.register(Device, DeviceAdmin)
我需要在设备管理页面上看到位置查找字段。但是,Location
与Device
相比Host
。
如何显示Location
字段以按设置管理页面上的位置>主机过滤设备类?
答案 0 :(得分:5)
您可以在list_filters
中链接字段,并在list_display
中使用ModelAdmin方法:
class DeviceAdmin(admin.ModelAdmin):
list_display = ('host', 'host_location', 'name', 'model', 'ip')
list_filter = (
('model', admin.RelatedOnlyFieldListFilter),
('host', admin.RelatedOnlyFieldListFilter),
'host__location',
)
def host_location(self, instance):
return instance.host.location
host_location.short_description = "Location"
host_location.admin_order_field = 'host__location'
admin.site.register(Device, DeviceAdmin)
更新在评论
中进行讨论要过滤外键(通过其任何字段,包括链接关系),您应该检查提供自动完成的工具。例如:django-autocomplete-light
。这将使您能够呈现这样的小部件:
注意:从Django 2.0开始,django-admin provides autocomplete fields与
django-autocomplete-light
开箱即用,代码较少。