简体   繁体   中英

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. 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?

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

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.

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']

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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