本文介绍了在 Admin 中提高 Django ForeignKey 字段的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,Django 的管理员将 admin 中的 ForeignKey 字段呈现为选择字段,将外表中的每条记录作为选项列出.在一个管理员可访问的模型中,我将 User 模型引用为 ForeignKey,并且由于我有数千个用户,Django 正在使用数千个选项填充 select.这导致管理页面加载速度非常慢,并且选择不是很有用,因为可能需要一段时间才能滚动浏览数千个选项以找到您想要的选项.

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.

更改此字段的呈现以提高页面加载和可用性的最佳方法是什么?我希望将选择字段替换为某种按钮以启动搜索表单弹出窗口,或通过 Ajax 搜索关键字以查找他们想要关联的特定用户的 Id 的文本字段.管理员是否有类似的内置函数,还是我必须从头开始编写?

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?

推荐答案

您可以使用为数不多的 Django 自动完成应用程序之一.在 Django 包 上查看它们.

You can use one of the few autocomplete apps for Django. Check them at Django Packages.

还有 django-extensionsForeignKeyAutocompleteAdmin 非常适合您的需求.

There's also django-extensions that have ForeignKeyAutocompleteAdmin that fit your needs pretty well.

这篇关于在 Admin 中提高 Django ForeignKey 字段的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 23:47