django管理员搜索多个单词

时间:2013-01-20 16:42:50

标签: python django django-admin

当搜索表达式有多个单词并且我想执行 startswith 搜索

时,我遇到麻烦search_fields

我有一个班级

class Foo(models.Model):
  kw = models.CharField(max_length = 255)
  ...

class FooAdmin(admin.ModelAdmin):
  search_fields = ('^kw',)

'^'表示我想执行STARTwith搜索。如果我正在寻找kw'foo fuu',django将执行查询:

select * from app_foo where `foo`.`kw` like 'foo%' and `foo`.`kw` like 'fuu%' 

此查询显然没有结果。如何让引擎查找'foo fuu%'

4 个答案:

答案 0 :(得分:12)

如何覆盖self.querysplit()不起作用?

from django.contrib.admin.views.main import ChangeList


class UnsplitableUnicode(str):
    "An object that behaves like a unicode string but cannot be split()"
    def split(self, *args, **kwargs):
        return [self]

class MultiWordSearchChangeList(ChangeList):
    "Changelist that allows searches to contain spaces"
    def get_query_set(self, request):
        self.query = UnsplitableUnicode(self.query)
        return super(MultiWordSearchChangeList, self).get_query_set(request)

class FooAdmin(admin.ModelAdmin):
    def get_changelist(self, request, **kwargs):
        return MultiWordSearchChangeList

答案 1 :(得分:2)

正如Thai Tran所说,它有点乱。以下是您必须编辑的部分。

from django.contrib import admin
from django.contrib.admin.views.main import ChangeList

class CustomChangeList(ChangeList):
    def get_query_set(self, request):
        #Basically copy and paste in entire function and edit the piece copied in here.

        if self.search_fields and self.query:
            orm_lookups = [construct_search(str(search_field))
                           for search_field in self.search_fields]
            for bit in self.query.split():
                or_queries = [models.Q(**{orm_lookup: bit})
                              for orm_lookup in orm_lookups]
                qs = qs.filter(reduce(operator.or_, or_queries))
            if not use_distinct:
                for search_spec in orm_lookups:
                    if lookup_needs_distinct(self.lookup_opts, search_spec):
                        use_distinct = True
                        break


class FooAdmin(admin.ModelAdmin):
    def get_changelist(self, request, **kwargs):
        return CustomChangeList

根据经验,覆盖ChangeList会引发问题。

答案 2 :(得分:1)

以下是可以对admin进行高级搜索的代码段链接:

http://djangosnippets.org/snippets/2322/

答案 3 :(得分:0)

这里是Mike Fogel's answer的略微修改版本,在最近的Django版本中似乎不起作用:

from django.contrib import admin
from django.contrib.admin.views.main import ChangeList


class UnsplittableStr(str):
    "An object that behaves like a unicode string but cannot be split()"
    def split(self, *args, **kwargs):
        return [self]


class MultiWordSearchMixin:
    def get_changelist(self, request, **kwargs):
        query = request.GET.get('q', '')
        request.GET = request.GET.copy()
        request.GET['q'] = UnsplittableStr(query)
        return ChangeList

现在,您可以从ModelAdmin类中的mixin继承:

class FooAdmin(MultiWordSearchMixin, admin.ModelAdmin):
    """Your ModelAdmin code here"""