2013-03-21 28 views
1

我已經在我的網站上設置Haystack搜索。搜索工作正常,我真的很喜歡它。我添加額外的上下文有問題。我想從3個模型中「推」對象到我的模板。 第一個對象是我的搜索結果,另外兩個應該是附加的。我的問題是:如何從另一個模型傳遞對象。這裏是我的search_indexes.py文件:如何添加Haystack的額外上下文

import datetime 
from haystack.indexes import * 
from haystack import site 
from filmy.models import Video, Page, Category 

class VideoIndex(SearchIndex): 
    text = CharField(document=True, use_template=True) 
    title = CharField(model_attr='title') 
    description = CharField(model_attr='description') 
    date = DateTimeField(model_attr='date') 

    def index_queryset(self, using=None): 
     # """Used when the entire index for model is updated.""" 
     return Video.objects.filter(date__lte=datetime.datetime.now()) 

    def extra_context(self): 
     return { 
      'categories': Category.objects.all().order_by('-name'), 
      'list_of_pages': Page.objects.all().order_by('id'), 
     } 

site.register(Video, VideoIndex) 

搜索工作正常,但我想有所有類別和所有頁面還清單列表(我使用它們在base.html文件模板我的解決辦法沒有按。 。「T工作,我想第二個與子類:

import datetime 
from haystack.indexes import * 
from haystack import site 
from filmy.models import Video, Page, Category 

class VideoIndex(SearchIndex): 
    text = CharField(document=True, use_template=True) 
    title = CharField(model_attr='title') 
    description = CharField(model_attr='description') 
    date = DateTimeField(model_attr='date') 

    def index_queryset(self, using=None): 
     # """Used when the entire index for model is updated.""" 
     return Video.objects.filter(date__lte=datetime.datetime.now()) 

site.register(Video, VideoIndex) 

class VideoSearchIndex(VideoIndex): 
    def extra_context(self): 
     extra = super(VideoSearchIndex, self).extra_context() 
     extra['categories'] = Category.objects.all().order_by('-name') 
     extra['list_of_pages'] = Page.objects.all().order_by('id') 
     return extra 

但這種代碼也不起作用,我不知道如何實現伊斯利其他模型,以我的搜索結果 感謝任何幫助

。!

回答

0

我fou nd解決我的問題。我解決不了extra_context函數,所以我用TEMPLATE_CONTEXT_PROCESSORS在我的模板中設置全局變量。

這是一個非常方便的解決方案,因爲我不需要在我的視圖中爲我的所有模型使用extra_context函數。我只是在一個定義中將全局變量設置在一個文件中。它增加了views.py文件的可讀性。

相關問題