我在 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。这是我当前的搜索索引:
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。但我不知道应该返回什么。
谢谢大家。
最佳答案
谢谢金部门,
但这是我的解决方案,具有简单的准备功能:
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
关于python - Django Haystack - 基于多个模型的搜索索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18926878/