You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
Django/doc/blog/search_indexes.py

28 lines
1.9 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 从Haystack库导入索引相关核心类
# 1. SearchIndex搜索索引基类定义搜索索引的核心结构如搜索字段
# 2. Indexable索引可访问性基类要求子类实现get_model方法指定关联的Django模型
from haystack import indexes
# 从当前应用blog的models.py导入Article模型用于将文章数据同步到搜索索引
from blog.models import Article
# 定义文章搜索索引类ArticleIndex继承自SearchIndex搜索索引核心和Indexable索引关联模型
# 作用告诉Haystack如何构建Article模型的搜索索引指定搜索字段、关联模型及索引数据范围
class ArticleIndex(indexes.SearchIndex, indexes.Indexable):
# 定义核心搜索字段text
# - document=True标记该字段为Haystack的"文档字段"(全文搜索的核心字段,所有搜索都会基于该字段匹配)
# - use_template=True指定使用模板来构建该字段的搜索内容模板路径默认是 templates/search/indexes/blog/article_text.txt
# 模板中可包含文章标题、正文、标签等需要被搜索的字段Haystack会将这些内容整合为text字段用于搜索
text = indexes.CharField(document=True, use_template=True)
# 实现Indexable基类的强制方法指定当前索引关联的Django模型
def get_model(self):
# 返回Article模型告诉Haystack该索引是为Article模型构建的
return Article
# 定义索引查询集指定哪些Article数据需要被纳入搜索索引
def index_queryset(self, using=None):
# using参数指定使用的搜索引擎如Elasticsearch、Whoosh默认None使用配置的默认引擎
# 过滤条件:仅将状态为"已发布"status='p')的文章纳入索引,草稿文章不参与搜索
return self.get_model().objects.filter(status='p')