Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use custom field for search in django admin

i have a model and is registered to the admin and i have used custom field to display in the list

class ReportsAdmin(admin.ModelAdmin):
    def investment(self, inst):
        return models.OrderDetail.objects.filter(user=inst.user).distinct().count()

    list_display = ['investment']
    search_fields = ['investment']

i want to search using the investment field in django admin but always getting Cannot resolve keyword 'investment' into field. choices are the Model fields.

is there any way by which i can search using the investment field?

like image 842
Exprator Avatar asked Jun 08 '17 10:06

Exprator


1 Answers

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
like image 86
daino3 Avatar answered Oct 04 '22 00:10

daino3