在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.objects.get(id=1)
articles = ArticlePage.objects.live() \
.filter(authors__author=author) \
.search('football')
但是在开发服务器日志中我收到此警告:
articles.ArticlePage: ArticlePage.search_fields contains non-existent field ‘author_id’
我的问题是:我这样做对吗?它有效,但警告让我认为可能有更正确的方法来实现相同的结果。
我还尝试使用FilterField('authors')
,它可以停止警告,但我不知道如何过滤它。
最佳答案
正确的方法在 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")]
),
]
让我知道它是否有效
关于django - Wagtail:通过模型过滤 ManyToMany 上的搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53848209/