尝试在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):
        ????


我已经看到on this question,答案是创建一个prepare_cnt_body。但是我不知道该退还什么。

谢谢大家。

最佳答案

谢谢Sectio Aurea,

但是这是我的解决方案,带有一个简单的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

07-26 04:43