Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Django-admin, how to add filter or search for foreign key select box?

I got a foreign key model with about 100,000 date.

It's too difficult to select the wanted data. So I'm wondering if there is a humanized way to add foreign key in django admin.

I have tried the raw_id_fields, it's useless.

this don't work.

like image 261
Sinux Avatar asked Feb 10 '23 03:02

Sinux


1 Answers

If you have a raw_id_fields set on your source admin class, you can set the search_fields on the target admin model to be able to filter the result based on the set search_fields, i.e. you will get a search input field in the select list popup, see image below.

enter image description here

Alternatively, django-2.0 just merged a pull request providing support for using select2 widgets in the django admin, see pull request for the full list of supported fields: https://github.com/django/django/pull/6385

With this you can use the autocomplete_fields on a foreignkey field on your source admin class and as before set the search_fields on the target admin class.

enter image description here

like image 169
holmberd Avatar answered Feb 13 '23 11:02

holmberd