2

I have two models as below. And I want to search and get the Brand objects both by Brand.name and by Item's titles which are related to the Brand.

class Brand(models.Model):
    name = models.CharField()
class Item(models.Model):
    title = models.CharField()
    brand = models.ForeignKey(Brand)

Then created Search index as below:

from models import Brand
from haystack import indexes

class BrandIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    name = indexes.CharField(model_attr='name')

    itemtitles = indexes.MultiValueField()
    def get_model(self):
        return Brand

    def prepare_itemtitles(self, obj):
        return [one['title'] for one in obj.item_set.values('title')]

Surely I added the object names into txt as:

{{ object.name }}
{{ object.itemtitles }}

But I failed to get the Brand searching by the keywords in itemtitles. I printed the content of "prepare_itemtitles" for each Brand object, no problem. And it could be searched by Brand.name.

I'm using haystack 2.0.0beta and whoosh2.4.1.

Can you help me understand how to implement my requirement of searching from the related model?

j0k
  • 22,600
  • 28
  • 79
  • 90
  • Try populating the required data inside the txt with a for loop. This is somewhat the same problem: https://stackoverflow.com/questions/5059301/how-do-i-add-related-data-to-a-haystack-model-index – vladimir.gorea Mar 08 '19 at 07:29

0 Answers0