如何配置Django Admin外键关联模型changelist的搜索功能
Django Admin跨模型搜索实现方案
前置配置修正
当前AirportAlternateName模型中外键的related_name='AirportOfficialName'配置语义和关联关系不匹配(该外键从别名指向主机场数据,反向关联返回的是别名列表,而非官方名称),建议修正为语义匹配的名称,修正后对应代码如下:
class AirportAlternateName(InfrastructureModel): parentAirport=models.ForeignKey( AirportAdministrativeData, on_delete=models.RESTRICT, limit_choices_to={'entryActiveYesNo': True}, verbose_name="Parent Airport", related_name='alternate_names' ) alternateAirportName=models.CharField( r"Airport's Alternate Name", max_length=100, null=False, blank=False, unique=True, help_text=r"Alternate name of the Airport, if any." )
注:该修改仅调整ORM层关联查询名称,不涉及数据库表结构变更,无需执行迁移命令。如果需要保留原有
related_name配置,后续代码中把alternate_names替换为AirportOfficialName即可。
Admin搜索规则配置
Django Admin的search_fields原生支持__双下划线语法实现跨关联模型查询,不需要自定义搜索方法,直接按关联路径配置字段即可,修正后的三个Admin类代码如下:
class AirportAdministrativeDataAdmin(admin.ModelAdmin): fields = ['officialAirportName', 'entryActiveYesNo'] list_display = ('officialAirportName', 'entryActiveYesNo') # 搜索范围:当前表官方名称、反向关联的别名表名称 search_fields = ['officialAirportName', 'alternate_names__alternateAirportName'] search_help_text="Search here for official/alternate name of any airport in the Database." class AirportAlternateNameAdmin(admin.ModelAdmin): fields = ['parentAirport', 'alternateAirportName', 'entryActiveYesNo'] list_display = ('parentAirport', 'alternateAirportName', 'entryActiveYesNo') # 搜索范围:当前表别名、外键关联主表的官方名称 search_fields = ['alternateAirportName', 'parentAirport__officialAirportName'] search_help_text="Search here for official/alternate name of any airport in the Database." class AirportLocationAdmin(admin.ModelAdmin): fields = ['parentAirport', 'latitude', 'longitude', 'airportAddress', 'airportState', 'entryActiveYesNo'] list_display = ('parentAirport', 'latitude', 'longitude', 'airportAddress', 'airportState', 'entryActiveYesNo') # 搜索范围:外键关联主表的官方名称、跨两层关联的别名表名称 search_fields = ['parentAirport__officialAirportName', 'parentAirport__alternate_names__alternateAirportName'] search_help_text="Search here for official/alternate name of any airport in the Database."
原有admin站点注册代码不需要修改,保持原有逻辑即可。
实现效果
配置完成后三个模型的changelist页面搜索框均支持同时匹配两类字段:
- 输入官方机场名,会返回所有匹配的主数据、关联别名、关联位置条目
- 输入机场别名,同样会返回对应的主数据、别名条目、关联位置条目
- 搜索默认采用大小写不敏感的模糊匹配规则,和Django Admin原生搜索逻辑一致
内容的提问来源于stack exchange,提问作者SOuser
相关产品推荐
相关产品推荐

