7

How do you make an abstract SearchIndex class, similar to how Django lets you make abstract base models?

I have several SearchIndexes that I'd like to give the same basic fields (object_id, timestamp, importance, etc). Currently, I'm duplicating all this code, so I'm trying to create a "BaseIndex" and simply have all the real index classes inherit from this.

I'm 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 the 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 these gives me error:

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

How do I inherit from a custom SearchIndex subclass?

4

2 回答 2

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...
于 2013-06-04T09:02:46.260 回答
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
于 2014-01-23T09:37:40.460 回答