![](/img/trans.png)
[英]Django Haystack/Solr: Show Solr field that is added in the prepare method of SearchIndex
[英]Django Haystack - A SearchIndex Based on Multiple Models
嘗試在Django上使用Haystack創建SearchIndex時遇到一些問題,但我不知道該怎么辦。
這是我的兩個模型 :
# Meta: stores meta data about tutorials (category, title)
class Meta(models.Model):
"""
Database [tutorial.meta]
"""
mta_title = models.CharField(max_length=TUTORIAL_TITLE_MAX)
mta_views = models.PositiveIntegerField(default=0)
# Contents: stores the tutorial text content
class Contents(models.Model):
"""
Database [tutorial.contents]
"""
tut_id = IdField()
cnt_body = BBCodeTextField()
現在,我要基於以下三個字段來創建我的SearchIndex:mta_title,mta_views和cnt_body。 這是我當前的SearchIndex:
from haystack import indexes
from tutorial.models import Meta as TutorialMeta
from account.models import Profile as UserProfile
class TutorialMetaIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
title = indexes.CharField(model_attr='mta_title')
views = indexes.CharField(model_attr='mta_views')
# Haystack reserves the content field names for internal use
cnt_body = indexes.CharField()
def get_model(self):
return TutorialMeta
def index_queryset(self, using=None):
"""Used when the entire index for model is updated."""
return self.get_model().objects.all()
def prepare_cnt_body(self, obj):
????
我已經看到了這個問題 ,答案是創建一個prepare_cnt_body。 但是我不知道該退還什么。
謝謝大家。
謝謝Sectio Aurea,
但是這是我的簡單解決方案的解決方案:
class TutorialIndex(indexes.SearchIndex, indexes.Indexable):
"""
Index the tutorials
"""
text = indexes.CharField(document=True, use_template=True)
tut_id = indexes.IntegerField(model_attr='tut_id')
cnt_body = indexes.CharField(model_attr='cnt_body')
mta_title = indexes.CharField()
mta_views = indexes.CharField()
def get_model(self):
"""
Return the current model
"""
return TutorialContents
def get_updated_field(self):
"""
Return the update date tracking field
"""
return "cnt_date"
def index_queryset(self, using=None):
"""
Used when the entire index for model is updated.
"""
return self.get_model().objects.all()
def prepare(self, object):
"""
Prepare the search data
"""
self.prepared_data = super(TutorialIndex, self).prepare(object)
# Retrieve the tutorial metas and return the prepared data
meta = get_tutorial_meta(id=object.tut_id)
self.prepared_data['mta_title'] = meta.mta_title
self.prepared_data['mta_views'] = meta.mta_views
return self.prepared_data
無需“准備”。 只需使用您在“文本”字段中引用的模板即可。 在您的應用程序“ myapp”中,創建文件模板/search/indexes/myapp/tutorialmeta_text.txt。 在此文件中,使用標准Django模板語言模型引用創建以下條目,例如:
{{object.mta_title}}
{{object.mta_views}}
{{object.contents.cnt_body}}
然后,您需要使用新模板(./manage.py rebuild_index)重建索引。 這將針對每個對象對三個引用字段中的每一個進行索引。 使用此方法,您還可以省略SearchIndex類中的“標題”,“視圖”和“ cnt_body”字段以及“准備”方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.