回到顶部

阅读目录

Django admin ForeignKey 字段增加搜索选择框

产生背景

当 ForeignKey 数据过多,手动在后台添加时不方便找到自己的想要数据,遂想要一个可以搜索检索数据功能。

检索文档

https://stackoverflow.com/questions/30214469/in-django-admin-how-to-add-filter-or-search-for-foreign-key-select-box/50356922

With this you can use the autocomplete_fields on a foreignkey field on your source admin class and as before set the search_fields on the target admin class.

配置 admin

class AnchorBindAgentAdmin(admin.ModelAdmin):
    list_display = ["agent", "anchor", "proportion", "start_time", "end_time", "create_time"]
    list_display_links = ["agent", "anchor", "proportion", "start_time", "end_time", "create_time"]
    list_filter = ["agent", "anchor", "start_time", "end_time"]
    list_per_page = 20  # 每页数量
    readonly_fields = ["start_time"]
    autocomplete_fields = ["anchor"]  # 带有搜索框的外键选择框

配置后效果

注意事项

被搜索的字段需要在其对应对的模型的 admin 中加入到 search_field

^_^
请喝咖啡 ×

文章部分资料可能来源于网络,如有侵权请告知删除。谢谢!

前一篇: MacOS mysqlclient ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.
下一篇: django admin 列表禁用删除操作,编辑页面禁用删除按钮
captcha