13

I'm trying to configure the Django admin bindings for a specific model so that I can quickly filter by the exact value of a specific field. I know I can manually tamper with the GET parameters to do this:

?fieldname__exact=foobar

What I can't seem to do, is get the sidebar to display a small form where I can enter this value. I know I can add fieldname to list_filter, but that doesn't scale well beyond tens of unique values. I looked into django-advanced-filters for a bit, but it doesn't seem to be compatible with Django 1.11.

How can I implement exact search for a specific field in the Django admin?

Pieter
  • 893
  • 1
  • 8
  • 20

1 Answers1

33

a little late but i hope it still helps someone

the possible configurations for the searchfield are listed at http://www.django-rest-framework.org/api-guide/filtering/#searchfilter.

'^' Starts-with search.
'=' Exact matches. (case-insensitive)
'@' Full-text search. (Currently only supported Django's MySQL backend.)
'$' Regex search. (Only with Django Rest Framework)

In your case, just add

search_fields = ['=fieldname', 'otherfieldname']

to your admin.

Update: Since Django 2.1 it is also possible to add lookups to the search fields (e.g. 'fieldname__exact'). You can find infos in the Django Docs, as well as the possible Lookups

lilaLeon
  • 476
  • 3
  • 5
  • 1
    Interesting feature, but unfortunately that doesn't allow for a separate search boxes specifically for one field, does it? – Pieter Sep 22 '17 at 06:27
  • No it is the same searchfield for every field. I'm afraid a separate field is only possible with HTML/Javascript. – lilaLeon Sep 25 '17 at 09:04
  • Also documented in the [Django docs](https://docs.djangoproject.com/en/1.11/ref/contrib/admin/#django.contrib.admin.ModelAdmin.search_fields) – Fush Oct 26 '17 at 02:22
  • 1
    The regex search is not available in django admin, only in DRF. Also, the exact match is case insensitive. – nbeuchat Jul 25 '18 at 23:28
  • 1
    @Pieter did you find any solution for separate search boxes specifically for one field? – Giorgi Beria Mar 14 '20 at 05:26
  • From what I recall we ended up manually creating separate filters for each field I wanted a separate search box for. More of a last resort than a real solution, but it was good to have a workaround. – Pieter Mar 16 '20 at 08:01