[Fixed]-Django form with ManyToMany field with 500,000 objects times out

8๐Ÿ‘

โœ…

You need to create a custom widget for this field that lets you autocomplete for the correct record. If you donโ€™t want to roll your own: http://django-autocomplete-light.readthedocs.io/

Iโ€™ve used this for its generic relationship support, the M2M autocomplete looks pretty easy and intuitive as well. see video of use here: http://www.youtube.com/watch?v=fJIHiqWKUXI&feature=youtu.be

After reading your comment about needing it outside the admin, I took another look at the django-autocomplete-light library. It provides widgets you can use outside the admin.

from dal import autocomplete
from django import forms

class PersonForm(forms.ModelForm):
    class Meta:
        widgets = {
            'myformfield': autocomplete.ModelSelect2(
                # ...
            ),
        }

8๐Ÿ‘

Since Django 2.0, Django Admin ships with an autocomplete_fields attribute that generates autocomplete widgets for foreign keys and many-to-many fields.

class PhoneNumbersAdmin(admin.ModelAdmin):
    search_fields = ['number']

class ClientAdmin(admin.ModelAdmin):
    autocomplete_fields = ['number']

Note that this only works in the scope of Django admin of course. To get autocomplete fields outside the admin you would need an extra package such as django-autocomplete-light as already suggested in other answers.

๐Ÿ‘คAntoine Pinsard

4๐Ÿ‘

Out of the box, the model admin has a raw_id_fields option that let your page load much quicker. However, the user interface of raw id fields isnโ€™t very intuitive, so you might have to roll your own solution.

๐Ÿ‘คAlasdair

0๐Ÿ‘

We use this 3rd party widget for this:

https://github.com/crucialfelix/django-ajax-selects

Btw, your โ€˜exampleโ€™ above is really bad DB design for a bunch of reasons. You should just have the phone number as a text field on the Client model and then you would have none of these issues. ๐Ÿ˜‰

๐Ÿ‘คApollo Data

Leave a comment