【问题标题】:Haystack index objects using their reverse relation使用反向关系的 Haystack 索引对象
【发布时间】:2016-12-10 01:29:15
【问题描述】:

我有两个模型:

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)

我有一个大海捞针搜索索引来索引所有Questionquestion_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 编制索引,以便在搜索Questions 时获得与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

终极问题:如何使用这个QuestionIndex 类索引所有response_text

【问题讨论】:

    标签: python django search tastypie django-haystack


    【解决方案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()])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-04
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-04-29
      • 2011-05-20
      相关资源
      最近更新 更多