django admin 中对自定义字段进行搜索

我想在 django admin 中使用investment字段进行搜索,但总是得到Cannot resolve keyword 'investment' into field.选项是 Model 字段。

有什么方法可以使用investment字段进行搜索?

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
    list_display = ['investment']
    search_fields = ['investment']

 

posted @ 2023-04-25 21:53  super_ip  阅读(27)  评论(0编辑  收藏  举报