我在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基于以下3个字段: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):
????
我见过on this question,答案是创建一个prepare_cnt_body。但我不知道应该归还什么。
谢谢大家。
答案 0 :(得分:1)
谢谢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
答案 1 :(得分:0)
无需'准备'。只需使用您在“文本”字段中引用的模板即可。在你的应用程序'myapp'中,创建文件templates / search / indexes / myapp / tutorialmeta_text.txt。在此文件中,使用标准Django模板语言模型引用创建以下条目,如:
{{object.mta_title}}
{{object.mta_views}}
{{object.contents.cnt_body}}
然后,您需要使用新模板重建索引(./manage.py rebuild_index)。这将针对每个对象索引三个引用字段中的每一个。使用此方法,您还可以省略SearchIndex类中的“title”,“views”和“cnt_body”字段,以及“prepare”方法。