Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 210
Cerin Avatar asked Feb 24 '11 17:02

Cerin


2 Answers

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

like image 81
Daniel Roseman Avatar answered Oct 05 '22 07:10

Daniel Roseman


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.

like image 41
Etienne Avatar answered Oct 05 '22 06:10

Etienne