【问题标题】:How to make an abstract Haystack SearchIndex class如何制作一个抽象的 Haystack SearchIndex 类
【发布时间】:2013-06-03 15:14:07
【问题描述】:

你如何制作一个抽象的 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 子类继承?

【问题讨论】:

标签: python django django-haystack


【解决方案1】:

只是不要将 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...

【讨论】:

  • 这对我有用。我不相信你需要class Meta: abstract = True 位才能工作。
  • 如果您想阻止其他开发人员尝试直接使用您的类,abstract = True 很有用。
  • 实际上,这是针对 django 模型的,对于索引它似乎不起作用,我可能只是从问题中复制了它。
  • 对不起,我应该在我的评论中包含草垛索引不需要的内容。但无论如何,答案都对我有所帮助。谢谢!
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    • 2020-01-19
    • 2022-01-18
    • 2018-06-28
    • 1970-01-01
    • 1970-01-01
    • 2016-02-28
    相关资源
    最近更新 更多