[Answered ]-How to setup search in django-admin changelists in models related through ForeignKeys?

1πŸ‘

βœ…

To add a search field from a related model you need to use the same notation as with filter(), i.e. a path with names of the fields separated with double-underscores.

First search field

To add AirportAdministrativeData.officialAirportName as search field to the change list of AirportLocation you add this: 'parentAirport__officialAirportName.

Second search field

For the 2nd search field to the alternate name you need to go one level deeper and use the "related name", which is the reverse relation from AirportAdministrativeDataAdmin to AirportAlternateNameAdmin:

'parentAirport__AirportOfficialName__alternateAirportName'

Result

Search fields are combined with OR by default, so you can add the 2nd search field and it will filter objects which match one or the other:

class AirportLocationAdmin(admin.ModelAdmin):
    ...
    search_fields = [
        'parentAirport__officialAirportName',
        'parentAirport__AirportOfficialName__alternateAirportName'
    ]
    ...

Two additional suggestions if I may:

  • In Python properties of a method are supposed to be in snake case, like you see in the Admin classes. So I would suggest to rename all field names of your models and also the "related_name" definitions. See PEP8 for more infos about the official coding style for Python
  • the "r" in front of your strings is obsolete. It means that you are defining regular expressions strings, which would not make sense here. Would suggest to remove the "r", you do not need it.
πŸ‘€Erik Kalkoken

Leave a comment