How to use custom field for search in django admin
In software, anything is possible... SMH at the accepted answer. You have to override get_search_results
.
from django.db.models import Count
class ReportsAdmin(admin.ModelAdmin):
def investment(self, inst):
return models.OrderDetail.objects.filter(user=inst.user).distinct().count()
list_display = ['investment']
search_fields = ['investment']
def get_search_results(self, request, queryset, search_term):
# search_term is what you input in admin site
search_term_list = search_term.split(' ') #['apple','bar']
if not any(search_term_list):
return queryset, False
if 'investment' in search_term_list:
queryset = OrderDetail.objects.annotate(
user_count=Count('user')
).filter(user_count__gte=search_term_list['investment'])
return queryset, False
Well, this is not allowed:
ModelAdmin.search_fields
Set search_fields to enable a search box on the admin change list page. This should be set to a list of field names that will be searched whenever somebody submits a search query in that text box.
These fields should be some kind of text field, such as CharField or TextField. You can also perform a related lookup on a ForeignKey or ManyToManyField with the lookup API “follow” notation:
You don't have such a field at all (never mind that the field has to be a TextField or CharField). What you actually have is a method in your admin class, which cannot be searched at the database level. Ie what's in the search_fields translates to like '%search_term%'
type queries executed at the db.