1

I have a similar situation as this post in which I encounter a slow page loading as I have thousands of entries in a foreignkey field.

At modelform, is there a way to improve the page loading while keeping the dropdown function? I have used select2 to efficiently find the chosen item in the dropdown, thus want to keep this function.

Fxs7576
  • 1,259
  • 4
  • 23
  • 31
  • While not keeping the dropdown, we've used `raw_id_fields` in cases like these, which is just one more click: https://docs.djangoproject.com/en/2.0/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields – FlipperPA Jun 30 '18 at 17:25

1 Answers1

0

Django has to fetch all those foreignkey objects from database and then render them as HTML. This is why it takes a lot of time. Fetching from database can be pretty quick if you cache everything, but rendering to HTML will still be a problem.

Here's a solution that I think would work best:

  1. Exclude that ForeignKey field from your form.
  2. Instead, just create a blank input field. You'll have to capture user's input via JavaScript and send that value to your backed to fetch suggestions. In fact, select2 supports fetching data from backend via AJAX, So, half of your work is done.
  3. Create a view which will take that AJAX request and search the database for suggestions and send them back to the client.

And you're done.

xyres
  • 20,487
  • 3
  • 56
  • 85