在django管理搜索栏中,如果我有一个带有column = fruit_name的模型 我想在所有实例中使用fruit_name = banana或apple来搜索该列,这将显示所有的香蕉和苹果,我该怎么做?
答案 0 :(得分:7)
覆盖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
答案 1 :(得分:1)
在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
的文档