[我们具有一个Blog模型的设置,该模型与BlogPageCategory有许多联系,并且我们有一个“ recent blog posts”流字段块,可让您指定是显示X个最新博客帖子还是X个最新博客帖子的卡片具体类别。
因此,我们从以下代码开始:
from wagtail.core import blocks
class RecentBlogEntries(blocks.StructBlock):
title = blocks.CharBlock(
required=True,
)
category_filter = blocks.ChoiceBlock(
label='Filter by Category',
required=False,
choices=[
('all', 'All'),
('First Category', 'First Category'),
('...',. '...'),
],
)
...
但是对类别进行硬编码是很愚蠢的,并且能够从“列表的当前位置,基于BlogPageCategory的CMS数据”中选择类别会更加方便。但是,以下代码(当然)变成了同样硬编码的迁移:
from wagtail.core import blocks
from ... import BlogPageCategory
class RecentBlogEntries(blocks.StructBlock):
title = blocks.CharBlock(
required=True,
)
choices = [ (cat.name, cat.name) for cat in BlogPageCategory.objects.all()]
choices.sort()
choices.insert(0, ('all', 'All'))
category_filter = blocks.ChoiceBlock(
label='Filter by Category',
required=False,
choices=choices,
)
...
有没有办法使它成为动态值,而不是由makemigrations
固定的列表?
[ChoiceBlock
接受可调用的函数作为choices
参数:
def get_categories():
return [(cat.name, cat.name) for cat in BlogPageCategory.objects.all()]
class RecentBlogEntries(blocks.StructBlock):
title = blocks.CharBlock(
required=True,
)
category_filter = blocks.ChoiceBlock(
label='Filter by Category',
required=False,
choices=get_categories,
)
可调用对象需要在模块的顶层定义,以便迁移可以对其进行引用(即,它不能是类上的方法),并且如果随后对其进行了移动或重命名,则可以将需要相应地编辑迁移。