2

私は以下の2つのモデルを持っています。そして、Brand.name と、Brand に関連する Item のタイトルの両方で、Brand オブジェクトを検索して取得したいと考えています。

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

次に、以下のように検索インデックスを作成しました。

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')]

確かに、オブジェクト名を次のようにtxtに追加しました。

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

しかし、itemtitles のキーワードでブランドを検索できませんでした。Brand オブジェクトごとに「prepare_itemtitles」の内容を出力しましたが、問題ありません。Brand.name で検索できます。

haystack 2.0.0beta と whoosh2.4.1 を使用しています。

関連モデルから検索するという私の要件を実装する方法を理解するのを手伝ってもらえますか?

4

0 に答える 0