有没有办法在管理员搜索中搜索多个术语?姜戈

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

在 django 管理搜索栏中,如果我有一个带有列的模型 = fruit_name 我想在该列中搜索所有带有 fruit_name = banana 或 apple 的实例,这将显示所有香蕉和苹果,我该怎么做?

在您的 admin.py 文件中,您可以自定义模型的呈现方式。

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)

您可以自定义要搜索的字段、要显示的字段、顺序等。

查看有关 admin page

的文档

重写 ModelAdmin.get_search_results` 方法:

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

在我的例子中,使用@catavaran 的回答会破坏过滤器 here。我想出了以下解决方法:

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

class MyAdmin(admin.ModelAdmin):
    ...
    def get_search_results(self, request, queryset, search_term):
        orig_queryset = queryset
        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))

    queryset = queryset & orig_queryset

    return queryset, use_distinct

这确保在我们使用 queryset |= self.model.objects.filter(reduce(or_, q_objects)) 时不会覆盖 ant 之前的过滤。另一方面,orig_queryset 的使用确保任何选定的过滤器也得到应用。