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

Cer*_*rin 7 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...
Run Code Online (Sandbox Code Playgroud)

但这给了我错误:

NotImplementedError: You must provide a 'model' method for the '<myapp.search_indexes.BaseIndex object at 0x18a7328>' index.
Run Code Online (Sandbox Code Playgroud)

所以我尝试了:

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()
Run Code Online (Sandbox Code Playgroud)

但这些给了我错误:

SearchFieldError: The index 'PersonIndex' must have one (and only one) SearchField with document=True.
Run Code Online (Sandbox Code Playgroud)

如何从自定义SearchIndex子类继承?

Ste*_*ger 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...
Run Code Online (Sandbox Code Playgroud)