2013-12-09 36 views
3

我試圖在我的Django應用程序中使用django-haystack + whoosh。我的指數類看起來像這樣如何使用django-haystack SearchQuerySet過濾結果?

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) 

有什麼建議嗎?謝謝

+0

您是否記得在'ArticleIndex'中更改後調用'manage.py update_index'? – maciek

+0

我不能相信我記得這一點,但是是的! – AndrewSmiley

回答

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的草垛2.1.0型indexes.CharField的屬性使用.filter() 。也許有人可以提供更多的細節,但這對我來說很有用。