默认情况下,Django 的 admin 将 admin 中的foreignkey字段呈现为选择字段,将外表中的每条记录作为选项列出。在一个管理员可访问的模型中,我将用户模型引用为外键,并且由于我有数千个用户,Django 正在使用数千个选项填充选择。这导致管理页面加载极其缓慢,并且选择不是很有用,因为可能需要一段时间才能滚动浏览数千个选项才能找到您想要的选项。
为了提高页面加载和可用性,更改此字段的呈现的最佳方法是什么?我希望将选择字段替换为某种按钮来启动搜索表单弹出窗口,或者替换为通过 Ajax 搜索关键字以查找他们想要关联的特定用户的 ID 的文本字段。管理员是否有类似的内置功能,或者我必须从头开始编写它?
By default, Django's admin renders ForeignKey fields in admin as a select field, listing every record in the foreign table as an option. In one admin-accessible model, I'm referencing the User model as a ForeignKey, and since I have thousands of users Django is populating the select with thousands of options. This is causing the admin page to load incredibly slowly, and the select is not very useful since it can take a while to scroll through thousands of options to find the one you want.
What's the best way to change the rendering of this field in order to improve page load and usability? I'd like the select field to be replaced with some sort of button to launch a search form popup, or a text field that searches keywords via Ajax to find the Id for the specific User they want to associate. Does admin have anything like this builtin, or would I have to write this from scratch?
发布评论
评论(5)
添加
raw_id_fields
您的模型仅显示 ID 而不是下拉列表。Add
raw_id_fields
to your model to only show the ID instead of a dropdown.你是对的,Cerin,速度变慢的原因是 Django 使用太多选项填充
有趣的是,Django 2.0 在管理站点上引入了一项新功能,称为
autocomplete_fields
,我认为您会发现在这种情况下很有用。它使用 AJAX。You're right, Cerin, the cause of the slowdown is because Django is populating the
<select>
element with too many options. You might want to use an autocomplete element instead.Interestingly, Django 2.0 has introduced a new feature on the admin site, called
autocomplete_fields
, which I think you will find useful in this case. It uses AJAX.您可以使用 Django 的少数自动完成应用程序之一。在 Django 包 中检查它们。
还有 django-extensions 具有
ForeignKeyAutocompleteAdmin
非常适合您的需求。You can use one of the few autocomplete apps for Django. Check them at Django Packages.
There's also django-extensions that have
ForeignKeyAutocompleteAdmin
that fit your needs pretty well.另一种选择是添加
readonly_fields
而不是raw_id_fields
Another option is to add
readonly_fields
instead ofraw_id_fields