简体   繁体   English

提高管理员中Django ForeignKey字段的性能

[英]Improving Performance of Django ForeignKey Fields in Admin

By default, Django's admin renders ForeignKey fields in admin as a select field, listing every record in the foreign table as an option. 默认情况下,Django的管理员将admin中的ForeignKey字段作为选择字段呈现,列出外表中的每个记录作为选项。 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. 在一个可管理的模型中,我将User模型引用为ForeignKey,因为我有成千上万的用户,Django正在使用数千个选项填充选择。 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. 我希望将select字段替换为某种按钮以启动搜索表单弹出窗口,或者通过Ajax搜索关键字以查找要关联的特定用户的Id的文本字段。 Does admin have anything like this builtin, or would I have to write this from scratch? 管理员是否有类似内置的内容,或者我是否必须从头开始编写?

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

You can use one of the few autocomplete apps for Django. 您可以使用Django的少数自动完成应用程序之一。 Check them at Django Packages . Django Packages查看它们。

There's also django-extensions that have ForeignKeyAutocompleteAdmin that fit your needs pretty well. 还有django-extensions ,它们具有适合您需求的ForeignKeyAutocompleteAdmin

You're right, Cerin, the cause of the slowdown is because Django is populating the <select> element with too many options. 你是对的,Cerin,减速的原因是因为Django用太多选项填充<select>元素。 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. 有趣的是,Django 2.0在管理站点上引入了一个名为autocomplete_fields的新功能,我认为在这种情况下你会觉得很有用。 It uses AJAX. 它使用AJAX。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM