Wagtail 封装了便利的字段搜索能力,在不做任何设置的情况下,它会默认搜索页面标题,任何需要被搜索的字段都可以直接在模型中进行定义,比如需要额外搜索品牌名称字段:

from django.db import models
from wagtail.core.models import Page
from wagtail.search import index

class CompanyPage(Page):
    brand = models.CharField(
        '品牌名', blank=False, null=False, max_length=250)

    search_fields = Page.search_fields + [、
        index.SearchField('brand'),
    ]

索引字段为外键

当需要被搜索的字段为外键时,如果像其他标准字段一样引用,则会报错:

FieldError at /zh-hans/company/
Related Field got invalid lookup: icontains

比如我用 snippets 定义了一个分类:

from django.db import models
from wagtail.core.models import Page
from wagtail.search import index

class CompanyPage(Page):
    category = models.ForeignKey(
        'Category', null=True, blank=True, on_delete=models.SET_NULL,
        related_name='+'
    )
    brand = models.CharField(
        '品牌名', blank=False, null=False, max_length=250)

    search_fields = Page.search_fields + [、
        index.SearchField('brand'),
        index.SearchField('category__name'),
    ]

设置搜索字段时则需要采用 foreignKey__name 的格式引用,如上 index.SearchField('category__name')

注意:双下划线!!!

Reference