How to create an abstract SearchIndex Haystack class

How do you create an abstract SearchIndex class, similar to how Django allows you to create abstract base models?

I have several SearchIndexes that I would like to provide the same base fields (object_id, timestamp, importance, etc.). I am currently duplicating all this code, so I am trying to create a "BaseIndex" and just inherit all the real index classes.

I tried:

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... 

but this gives me an error:

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

so I then tried:

 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() 

but this gives me an error:

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

How to inherit from a custom subclass of SearchIndex?

+7
source share
2 answers

Just don't include indexes.Indexable as a parent in anything you don't want to index.

So, change your first example.

 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... 
+13
source
 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 
+4
source

All Articles