12

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

4

3 回答 3

18

覆盖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
于 2015-01-23T00:05:47.707 回答
2

在您的 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)

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

检查有关管理页面的文档

于 2015-01-22T23:44:12.290 回答
1

就我而言,使用@catavaran 的答案会破坏过滤器,如这里所要求的那样。我想出了以下解决方法:

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

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

于 2021-09-14T01:02:36.217 回答