如何制作一个抽象的Haystack SearchIndex类

时间:2013-06-03 15:14:08

标签: python django django-haystack

如何制作抽象的SearchIndex类,类似于Django如何制作抽象基础模型?

我有几个SearchIndexes,我想提供相同的基本字段(object_id,时间戳,重要性等)。目前,我正在复制所有这些代码,所以我试图创建一个“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子类继承?

2 个答案:

答案 0 :(得分: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...

答案 1 :(得分: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