在一个基于Wagtail的网站中,我有一个ArticlePage
模型,该模型与Author
代码段模型具有多对多关系,例如:
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.core.models import Orderable, Page
from wagtail.search import index
from wagtail.snippets.models import register_snippet
class ArticlePage(Page):
search_fields = Page.search_fields + [
index.FilterField('author_id'),
]
@register_snippet
class Author(models.Model):
name = models.CharField(max_length=255, blank=False)
class ArticleAuthorRelationship(Orderable, models.Model):
author = models.ForeignKey('Author', on_delete=models.CASCADE, related_name='articles')
page = ParentalKey('ArticlePage', on_delete=models.CASCADE, related_name='authors')
我希望能够搜索ArticlePage
的 并通过特定的Author
对其进行过滤,我可以这样做:
author = Author.objects.get(id=1)
articles = ArticlePage.objects.live() \
.filter(authors__author=author) \
.search('football')
但是在开发服务器日志中,我得到以下警告:
articles.ArticlePage:ArticlePage.search_fields包含不存在的字段“ author_id”
我的问题是:我这样做正确吗?有效,但是警告使我认为可能会有更正确的方法来达到相同的结果。
我也尝试过使用FilterField('authors')
来停止警告,但是我无法确定如何对此进行过滤。
答案 0 :(得分:0)
正确的方法在documentation
中进行了说明这是官方文档中共享的示例:
from wagtail.search import index
class Book(models.Model, index.Indexed):
...
search_fields = [
index.SearchField('title'),
index.FilterField('published_date'),
index.RelatedFields('author', [
index.SearchField('name'),
index.FilterField('date_of_birth'),
]),
]
因此,您应该输入:
class ArticlePage(Page):
search_fields = Page.search_fields + [
index.RelatedFields(
"author", [index.SearchField("id")]
),
]
让我知道它是否有效