Django管理员将Field与另一个模型相关联

时间:2016-03-15 09:36:30

标签: django model foreign-keys

以下是我的模特:

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)

我需要在设备管理页面上看到位置查找字段。但是,LocationDevice相比Host

如何显示Location字段以按设置管理页面上的位置>主机过滤设备类?

1 个答案:

答案 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。这将使您能够呈现这样的小部件:

enter image description here

  

注意:从Django 2.0开始,django-admin provides autocomplete fieldsdjango-autocomplete-light开箱即用,代码较少。