Is there a way to search for multiple terms in admin search? Django

In the admin django search bar, if I had a model with column = fruit_name and I wanted to find this column for all instances with fruit name = banana or apple, which will show all bananas and apples, how can I do this?

+6
source share
3 answers

Cancel the ModelAdmin.get_search_results ` method :

from operator import or_
from django.db.models import Q

class MyAdmin(admin.ModelAdmin):
    ...
    def get_search_results(self, request, queryset, search_term):
        queryset, use_distinct = super(MyAdmin, self).get_search_results(
                                               request, queryset, search_term)
        search_words = search_term.split()
        if search_words:
            q_objects = [Q(**{field + '__icontains': word})
                                for field in self.search_fields
                                for word in search_words]
            queryset |= self.model.objects.filter(reduce(or_, q_objects))
    return queryset, use_distinct
+7
source

In your admin.py file, you can customize the presentation of models.

class YourModelAdmin(admin.ModelAdmin):
       list_display = ('id_proveedor','anio','mes','fecha','fecha_mod','contacto','usuario','obs')
       list_display_links = ('id_proveedor','anio','mes','fecha','fecha_mod','contacto','usuario','obs')
       list_filter = ('id_proveedor','anio','mes')
       ordering = ['id_proveedor']
       search_fields = ('id_proveedor','anio','mes','contacot')
       list_per_page = 10

admin.site.register(YourModel, YourModelAdmin)

You can configure for which fields you want to search, fields that you want to display, organize, etc.

+1

Catavaran , !

:

Sorry, I can not comment on the answer above ....

0
source

All Articles