2016-08-04 5 views
1

У меня есть две модели: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) 

У меня есть один индекс поиска стог индексировать все question_textQuestion «s:

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

Вы можете поставить 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()])