Django admin search_fields with exception

With django search_fields on our django-admin site, we're looking for db for a lot of things. I want to have an exclude option on search_fields in a textbox (or any other way)

Example: in my admin file:

 search_fields = ('name', 'os', 'owner__first_name', 'owner__last_name',)

      

and on the web page I search for "John" -> getting some results including john lennon

I would really like to see "John {" exclude ":" Lennon "} '

-> this will give some results excluding john lennon

+3


source to share


1 answer


You can customize your search by specifying the get_search_results method in your ModelAdmin subclass. Haven't tested it though ..



class YourModelAdmin(admin.ModelAdmin):
    list_display = ('name', 'os')
    search_fields = ('name', 'os', 'owner__first_name', 'owner__last_name',)

    def get_search_results(self, request, queryset, search_term):
        queryset = super(YourModelAdmin, self).get_search_results(request, queryset, search_term)
        try:
            queryset |= self.model.objects.exclude(owner__last_name__iexact='lennon')
        except:
            pass
        return queryset

      

+1


source







All Articles