我有两个型号:
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
编制索引?
答案 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()])