干草堆索引对象使用它们的反向关系

时间:2016-08-04 04:43:19

标签: python django search tastypie django-haystack

我有两个型号:

class Question(models.Model):
    question_text = models.TextField()

class Response(models.Model):
    response_text = models.TextField()
    question = models.ForeignKey(Question, related_name='responses', on_delete=models.CASCADE)

我有一个haystack搜索索引来索引所有Question question_text

class QuestionIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    question_text = indexes.CharField(model_attr='question_text')
    def get_model(self):
        return Question

如何为所有response_text编制索引,以便在搜索Question时,我会收到与question_text匹配的所有问题以及所有与回复相匹配的问题response_text?我想要这样的东西:

class QuestionIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    question_text = indexes.CharField(model_attr='question_text')
    response_text = indexes.CharField(model_attr='responses__response_text')
    def get_model(self):
        return Question

终极问题:如何使用此response_text课程对所有QuestionIndex编制索引?

1 个答案:

答案 0 :(得分:1)

您可以为该字段提供prepare_ method以指定索引的数据:

class QuestionIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    question_text = indexes.CharField(model_attr='question_text')
    response_text = indexes.CharField()

    def prepare_response_text(self, obj):
        return ', '.join([r.response_text for r in obj.responses.all()])