2013-06-03 8 views
7

抽象的なSearchIndexクラスを作成するには、Djangoで抽象基盤モデルを作成する方法と同じようにしますか?抽象Haystack SearchIndexクラスを作成する方法

私は同じ基本フィールド(object_id、タイムスタンプ、重要度など)を与えたいいくつかのSearchIndexを持っています。現在、私はこのコードをすべて複製しているので、 "BaseIndex"を作成して、すべての実際のインデックスクラスを継承させようとしています。

私が試したよ:

class BaseIndex(indexes.SearchIndex, indexes.Indexable): 
    text = indexes.CharField(document=True, use_template=True) 
    object_id = indexes.IntegerField() 
    timestamp = indexes.DateTimeField() 

    class Meta: 
     abstract = True 

class PersonIndex(BaseIndex): 
    ...other fields... 

をしかし、これは私にエラーを与える:

NotImplementedError: You must provide a 'model' method for the '<myapp.search_indexes.BaseIndex object at 0x18a7328>' index. 

ので、私はその後、試してみました:

class BaseIndex(object): 
    text = indexes.CharField(document=True, use_template=True) 
    object_id = indexes.IntegerField() 
    timestamp = indexes.DateTimeField() 

class PersonIndex(BaseIndex, indexes.SearchIndex, indexes.Indexable): 
    first_name = indexes.CharField() 
    middle_name = indexes.CharField() 
    last_name = indexes.CharField() 

をが、これらは私にエラーを与える:

SearchFieldError: The index 'PersonIndex' must have one (and only one) SearchField with document=True. 

カスタムSearchIndexサブクラスから継承するにはどうすればよいですか?

+0

A [検索インデックス 'Meta'クラス](http://django-haystack.readthedocs.org/en/latest/searchindex_api.html#modelsearchindex)属性を持っていない' abstract' ...どこから得たのか分からない? –

答えて

13

インデックス作成を望まないものには、indexes.Indexableを親として含めないでください。

最初の例を変更してください。

class BaseIndex(indexes.SearchIndex): 
    text = indexes.CharField(document=True, use_template=True) 
    object_id = indexes.IntegerField() 
    timestamp = indexes.DateTimeField() 

    class Meta: 
     abstract = True 

class PersonIndex(BaseIndex, indexes.Indexable): 
    ...other fields... 
+0

これは私のために働いた。私は 'class Meta:abstract = True'ビットが必要だとは思わない。 – Esteban

+0

'abstract = True'は他の開発者があなたのクラスを直接使用しようとするのを止めたい場合に便利です。 –

+1

実際、これはdjangoモデルのためです。インデックスの場合は動作していないようですが、おそらく質問からコピーしただけです。 –

4
class BaseIndex(indexes.SearchIndex): 
    model=None   

    text = indexes.CharField(document=True, use_template=True) 
    object_id = indexes.IntegerField() 
    timestamp = indexes.DateTimeField() 

    def get_model(self): 
     return self.model 

class PersonIndex(BaseIndex, indexes.Indexable): 
    first_name = indexes.CharField() 
    middle_name = indexes.CharField() 
    last_name = indexes.CharField() 

    def get_model(self): 
     return Person 
関連する問題