【问题标题】:Haystack SearchQuerySet won't filter on a CharField with one character (Whoosh / django-haystack)Haystack SearchQuerySet 不会过滤一个字符的 CharField (Whoosh / django-haystack)
【发布时间】:2013-12-24 20:09:05
【问题描述】:

我将 Django 1.5.1 与 django-haystack 2.1.0 和 whoosh 2.5.2 后端一起使用:

models.py:

GENDER_CHOICES = (
    (u'M', u'Male'),
    (u'F', u'Female'),
)

class Applicant(models.Model):

    gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
    first_name = models.CharField(max_length=64)
    last_name = models.CharField(max_length=64)

search_indexes.py:

class ApplicantIndex(indexes.SearchIndex, indexes.Indexable):

    text = indexes.CharField(document=True,use_template=True)
    gender = indexes.CharField(model_attr="gender")

搜索模板

{{ object.first_name }}
{{ object.last_name }}

在 django shell 中我正在尝试以下操作:

>>> from haystack.query import SearchQuerySet

>>> sqs=SearchQuerySet()
>>> sqs
[<SearchResult: tooldb.applicant (pk=u'1')>, <SearchResult: tooldb.applicant (pk=u'2')>]

>>> sqs[0].gender
u'M'     #<-- So this seems to be indexed

#but when i try:
>>> sqs.filter(gender='M')
[]     #<-- I get nothing ... ?

我在没有选择和 max_lenght > 1 的其他 CharFields 上尝试过,完全没有问题,干草堆过滤器应该是这样的。

我错过了什么?

【问题讨论】:

  • QuerySet 的过滤方法适用于一个字符作为查询,SearchQuerySet 什么也不返回。

标签: python django filter django-haystack whoosh


【解决方案1】:

这是我的解决方案:

class ApplicantIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    gender = indexes.CharField()

    def prepare_gender(self, obj):
        return obj.gender*3

现在你可以像这样过滤:

sqs.filter(gender='MMM')

【讨论】:

  • 似乎是一种解决方法.. 虽然有点脏。谢谢!
【解决方案2】:

好吧,我想我明白了..

似乎 haystack 与 whoosh 结合使用根本无法处理单个字符查询
这有点烦人,因为 SearchQuerySet 应该以 Django 的 QuerySet 工作方式实现。 (https://django-haystack.readthedocs.org/en/v2.1.0/searchqueryset_api.html#why-follow-queryset)

QuerySet 的过滤方法适用于一个字符作为查询,SearchQuerySet 什么也不返回。

这应该记录在某个地方...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 2011-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多