8

search_fields当搜索表达式有多个单词并且我想执行startwith搜索时,我无法使用

我有一堂课

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

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

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

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

这个查询显然给出了零结果。我应该怎么做才能使引擎寻找'foo fuu%'

4

4 回答 4

15

如何覆盖self.query所以split()不起作用?

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
于 2013-01-23T22:49:13.020 回答
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 会导致问题。

于 2013-01-23T14:39:37.907 回答
1

这是一个可以对管理员进行高级搜索的片段链接:

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

于 2013-01-26T01:18:05.880 回答
0

这是Mike Fogel 答案的略微修改版本,在最近的 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"""
于 2020-10-27T16:06:02.690 回答