Vladimir Akkerman
Vladimir Akkerman

Reputation: 131

Django admin related Field over another model

Here are my models:

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)

And here is the DeviceAdmin class:

class DeviceAdmin(admin.ModelAdmin):
    list_display=('host','name','model', 'ip')
    list_filter=(
        ('model', admin.RelatedOnlyFieldListFilter),
        ('host', admin.RelatedOnlyFieldListFilter),
    )    
admin.site.register(Device, DeviceAdmin)

I need to see Location lookup field on Device Admin page. However, Location is related to Device over Host.

How can I display Location field to filter Device class by Location->Host on Device Admin page?

Upvotes: 3

Views: 3856

Answers (1)

Antoine Pinsard
Antoine Pinsard

Reputation: 34942

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.

Upvotes: 5

Related Questions