提高 Django 管理中外键字段的性能

发布于 2024-10-19 05:26:32 字数 325 浏览 3 评论 0 原文

默认情况下,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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

埋葬我深情 2024-10-26 05:26:32

添加 raw_id_fields 您的模型仅显示 ID 而不是下拉列表。

Add raw_id_fields to your model to only show the ID instead of a dropdown.

牵强ㄟ 2024-10-26 05:26:32

你是对的,Cerin,速度变慢的原因是 Django 使用太多选项填充

有趣的是,Django 2.0 在管理站点上引入了一项新功能,称为 autocomplete_fields,我认为您会发现在这种情况下很有用。它使用 AJAX。

class ExampleAdmin(models.ModelAdmin):
    autocomplete_fields = ['example_field_user']

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.

class ExampleAdmin(models.ModelAdmin):
    autocomplete_fields = ['example_field_user']
夏见 2024-10-26 05:26:32

您可以使用 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.

方觉久 2024-10-26 05:26:32
class CustomAdmin(models.ModelAdmin):
    autocomplete_fields = ['foreignkey_field']
class CustomAdmin(models.ModelAdmin):
    autocomplete_fields = ['foreignkey_field']
醉生梦死 2024-10-26 05:26:32

另一种选择是添加 readonly_fields 而不是 raw_id_fields

Another option is to add readonly_fields instead of raw_id_fields

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文