[Django]-Django admin related Field over another model

5👍

You can chain fields in list_filters and use ModelAdmin methods in list_display:

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)

Update following the discussion in comments

To filter foreign keys (by any of its fields, chained relations included), you should checkout for a tool providing autocompletion. For instance: django-autocomplete-light. This will enable you to render such kind of widgets:

enter image description here

Note: Since Django 2.0, django-admin provides autocomplete fields that do the same as django-autocomplete-light out of the box, and with less code.

Leave a comment