wagtail search_fields上的片段与外键



我有一个代码片段,它是我的一个标准django模型的代理。search_fields在过滤标准字段时工作得很好,问题是我似乎无法获得外键的工作。这个页面底部有一个例子,展示了如何创建可搜索的片段:https://docs.wagtail.org/en/stable/topics/snippets.html

主模型有一个名为"day"它是day表的外键。一天有一个calendar_year,我希望能够过滤,而在wagtail片段区域搜索。str方法我能够在列表中显示名字,这里的问题是搜索。

建议吗?

@register_snippet
class EventSnippet(index.Indexed, Event):
# We make a proxy model just to be able to add to this file or potentially if we want custom methods on it.
panels = [
FieldPanel('name'),
]
search_fields = [
index.SearchField('day__calendar_year',  partial_match=True), # This prompts an error
index.SearchField('name', partial_match=True),
]
class Meta:
proxy = True
def __str__(self):
return f"{self.name} {self.day.calendar_year}"

当运行python manage.py update_index时,我得到以下警告:

EventSnippet.search_fields contains non-existent field 'day__calendar_year

你不能在SearchField中使用复杂的双下划线查找-搜索查询通过预先填充一个中心表(搜索索引)来工作,你要搜索的数据,这意味着你不能像使用标准数据库查询那样对它进行任意查找和转换。

但是,您可以在SearchField中使用任何方法或属性—不仅仅是数据库字段—所以您可以添加一个返回年份的方法,并使用它:

@register_snippet
class EventSnippet(index.Indexed, Event):
# ...
def get_year(self):
return self.day.calendar_year
search_fields = [
index.SearchField('get_year',  partial_match=True),
index.SearchField('name', partial_match=True),
]

最新更新