Django Haystack - 基于多个模型的搜索索引

2024-06-16 03:24:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试用Django上的Haystack创建搜索索引时遇到了一些问题,我不知道该怎么做。在

以下是我的两款车型

# 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。以下是我当前的搜索索引:

^{pr2}$

我看过on this question,答案是创建一个prepare_nt_主体。但我不知道我该还什么。在

谢谢大家。在


Tags: djangomodeltitlemodelscontentsbodydatabasetutorial
2条回答

不需要“准备”。只需使用您在“文本”字段中提到的模板。在应用程序“myapp”中,创建文件templates/search/index/myapp/tutorialmeta_文本.txt. 在此文件中,使用标准Django模板语言模型引用创建以下条目,如下所示:

{{object.mta_title}}
{{object.mta_views}}
{{object.contents.cnt_body}}

然后您需要使用新模板(/管理.py重建索引)。这将针对每个对象索引三个引用字段中的每一个。使用此方法,您还可以从SearchIndex类中省略“title”、“views”和“cnt_body”字段,以及“prepare”方法。在

谢谢你奥雷亚先生

但我的解决方案是使用一个简单的prepare函数:

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

相关问题 更多 >