M
M
maddread2016-03-27 08:16:42
Django
maddread, 2016-03-27 08:16:42

How to link three tables in django admin?

There are three models:

class Place(models.Model): 
    place_id = models.AutoField(primary_key=True)
    place = models.CharField(max_length=10, null=False)

class Host(models.Model): 
    host_id = models.AutoField(primary_key=True)
    place = models.ForeignKey('Place', 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)

In the django admin panel for the Device model, I also want to see Place, to limit the number of entries and make it more convenient to work with. But how to bind a Place if it refers to a Device through the Host model?
At the moment, the admin model for Device is as follows:
class DeviceAdmin(admin.ModelAdmin):
    list_display=('host', 'name', 'model', 'ip', 'slots')
    list_filter = (
        'host__place', 
        ('host', admin.RelatedOnlyFieldListFilter),
        ('model', admin.RelatedOnlyFieldListFilter),
    )
    def host_place(self, instance):
        return instance.host.place
    host_location.short_description = 'Place'
    host_location.admin_order_field = 'host__place'
admin.site.register(Device, DeviceAdmin)

Here, such a link only works for filtering when viewing. And I need Place to be visible when adding / editing Device.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oscar Django, 2016-03-27
@winordie

Check out https://github.com/digi604/django-smart-selects

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question