<a id="editors-picks"></a>

# 推广搜索结果

`searchpromotions` 模块提供了用于管理“推广搜索结果”并在搜索结果页中展示它们的模型和用户界面。

“推广搜索结果”让编辑能把相关内容显式关联到搜索词，这样结果页除了搜索引擎给出的结果之外，还可以包含人工策划的内容。

## 安装

`searchpromotions` 模块默认不启用。要安装它，请把 `wagtail.contrib.search_promotions` 加入项目 Django 设置文件中的 `INSTALLED_APPS`。

```python
INSTALLED_APPS = [
    ...

    'wagtail.contrib.search_promotions',
]
```

该应用包含迁移，所以安装后请确保运行 `migrate` 这个 django-admin 命令。

## 用法

安装后，“设置”菜单里应出现一个新的菜单项“推广搜索结果”。你可以在这里把页面指派给热门搜索词。

### 在搜索结果页中展示

要获取针对某个搜索查询的推广搜索结果列表，你可以使用 `wagtailsearchpromotions_tags` 模板标签库中的 `{% get_search_promotions %}` 模板标签：

```html+django
{% load wagtailcore_tags wagtailsearchpromotions_tags %}

...

{% get_search_promotions search_query as search_promotions %}

<ul>
    {% for search_promotion in search_promotions %}
        {% if search_promotion.page %}
            <li>
                <a href="{% pageurl search_promotion.page %}">
                    <h2>{{ search_promotion.page.title }}</h2>
                    <p>{{ search_promotion.description }}</p>
                </a>
            </li>
        {% else %}
            <li>
                <a href="{{ search_promotion.external_link_url }}">
                    <h2>{{ search_promotion.external_link_text }}</h2>
                    <p>{{ search_promotion.description }}</p>
                </a>
            </li>
        {% endif %}
    {% endfor %}
</ul>
```

### 管理已存储的搜索查询

`searchpromotions` 模块通过 `Query` 和 `QueryDailyHits` 模型记录搜索查询日志以及每日命中次数。

#### *class* wagtail.contrib.search_promotions.models.Query

#### *classmethod* get(query_string)

获取一条已存储的搜索查询，如果它不存在则创建一条新的。

#### add_hit(date=None)

通过创建新记录或增加已有记录的命中次数，为某个搜索查询再记录一次每日命中。默认使用当前日期，但也可以传入可选的 date 参数。

#### 示例搜索视图

下面是一个用于搜索页的 Django 视图示例，它会为搜索查询记录一次命中：

```python
from django.template.response import TemplateResponse

from wagtail.models import Page
from wagtail.contrib.search_promotions.models import Query


def search(request):
    search_query = request.GET.get("query", None)

    if search_query:
        search_results = Page.objects.live().search(search_query)
        query = Query.get(search_query)

        # 记录一次命中
        query.add_hit()
    else:
        search_results = Page.objects.none()

    return TemplateResponse(
        request,
        "search/search.html",
        {
            "search_query": search_query,
            "search_results": search_results,
        },
    )
```

## 管理命令

<a id="searchpromotions-garbage-collect"></a>

### `searchpromotions_garbage_collect`

```sh
./manage.py searchpromotions_garbage_collect
```

在流量很大的站点上，已存储的查询和每日命中日志可能会变得很大，你可能想清理掉旧记录。该命令会清掉所有超过一周的搜索查询日志（天数可通过 [`WAGTAILSEARCH_HITS_MAX_AGE`](../settings.html.md#wagtailsearch-hits-max-age) 设置调整）。
