19

Hypothetically: I have a model called Car, which relates to one user. My concern is within the default Django Admin. I assign a user to a car via a drop down (this is default Django behavior, so I'm told).

What happens when I have 1000s+ of users to pick from in the drop down. Does the admin deal with this, if so how?

Prometheus
  • 32,405
  • 54
  • 166
  • 302

3 Answers3

23

The default admin UI displays a dropdown list. Use the raw_id_fields option to get a pop-up window, via a search button. This window lets you find and select the linked object. See the documentation: https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.raw_id_fields

By default, Django’s admin uses a select-box interface () for fields that are ForeignKey. Sometimes you don’t want to incur the overhead of having to select all the related instances to display in the drop-down.

Tommy Hansen
  • 105
  • 1
  • 6
Mark Lavin
  • 24,664
  • 5
  • 76
  • 70
5

You can look into django-grappelli, which is an app that enhances the admin interface. The documentation describes an autocomplete for ForeignKey or ManyToMany relationships, using raw_id_fields.

msc
  • 3,780
  • 1
  • 22
  • 27
5

You can use django-select2 plugin https://github.com/applegrew/django-select2.

You can do something like:

from django_select2 import AutoModelSelect2Field

class CategoryChoices(AutoModelSelect2Field):
    queryset = models.Category.objects
    search_fields = ['name__icontains', 'code__icontains']

class NewsAdminForm(forms.ModelForm):
    category = CategoryChoices()

    class Meta:
        model = models.News
        exclude = ()

# register in admin
class NewsAdmin(admin.ModelAdmin):
    form = NewsAdminForm
admin.site.register(News, NewsAdmin)
Ranju R
  • 2,407
  • 21
  • 16
  • 3
    From the new `django-select2` repo: "Django's admin comes with builtin support for Select2 via the [autocomplete_fields](https://docs.djangoproject.com/en/stable/ref/contrib/admin/#django.contrib.admin.ModelAdmin.autocomplete_fields) feature." – hashlash Sep 28 '20 at 10:39