我有两个模型:
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)
我有一个干草堆搜索索引来索引所有
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
编制索引? 最佳答案
您可以为该字段提供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()])
关于python - 干草堆索引对象使用它们的反向关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38758617/