如何使用django-haystack SearchQuerySet过滤结果?

时间:2013-12-09 21:53:41

标签: django django-models django-haystack whoosh searchqueryset

我正在尝试在我的Django应用程序中使用django-haystack + whoosh。我的索引类看起来像这样

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

text = indexes.CharField(document=True, use_template=True)

title = indexes.CharField(model_attr='title')

abstract = indexes.CharField(model_attr='abstract')

def get_model(self):
    return Article

def index_queryset(self, using=None):
    return self.get_model().objects.all()

我的模型看起来像这样:

class Article(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(User)
abstract = models.CharField(max_length=500, blank=True)
full_text = models.TextField(blank=True)
proquest_link = models.CharField(max_length=200, blank=True, null=True)
ebsco_link = models.CharField(max_length=200, blank=True, null=True)

def __unicode__(self):
    return self.title

在我的模板中,我使用ajax搜索字段来查询文章模型并在同一页面中返回结果。本质上,ajax会将包含搜索文本的HttpPost请求触发到视图。在视图中,我想获得所有Article对象的抽象字段包含通过HttpPost发送的搜索文本。在我看来,我正在获取搜索文本,然后尝试获取类似

的模型
search_text = request.POST['search_text']
articles = SearchQuerySet().filter(abstract=search_text)

但它不会返回任何结果。如果我打电话

articles = SearchQuerySet().all()

它将返回本地测试数据库中的12个模型对象。但是,过滤器功能不会返回任何结果。我想要做的是相当于

articles= Article.objects.filter(abstract__contains=search_text)

有什么建议吗?谢谢

1 个答案:

答案 0 :(得分:3)

经过一番挖掘后,我将索引类更新为:

class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.NgramField(document=True, use_template=True)
    title = indexes.NgramField(model_attr='title')

    abstract = indexes.NgramField(model_attr='abstract')

    def get_model(self):
        return Article

    def index_queryset(self, using=None):
        return self.get_model().objects.all()

在django-haystack 2.1.0中对index.CharField类型的属性使用.filter()有问题。也许有人可以提供更多细节,但这对我有用。

相关问题