如何在 wagtail 中查询 Page 的子类?
How to query subclasses of Page in wagtail?
在首页和搜索页中,我想列出各种不同详细显示的页面。我按照文档写了下面的代码:
from wagtail.wagtailcore.models import Page
from my.models import ArticlePage, GalleryPage, VideoPage, SharedLinkPage
PAGE_TYPES = (ArticlePage, GalleryPage, VideoPage, SharedLinkPage,)
class HomePage(Page):
subpage_types = list(PAGE_TYPES)
def get_context(self, request):
context = super(HomePage, self).get_context(request)
context['posts'] = Page.objects.type(PAGE_TYPES).live()
context['recent_posts'] = Page.objects.type(PAGE_TYPES).live()
return context
这样的话,我只能得到[<Page: 1>, <Page:2>]
,我真正想要的是[<ArticlePage: 1>, <GalleryPage:2>]
。
我的问题在搜索页面中是相同的,但使用 search
查询:
Page.search('something', ArticlePage)
会更好:
search_backend.search('something').types(PAGE_TYPES).live()
您应该使用 specific
属性来获取每个页面的最具体的子类形式:
此外,PageQuerySet
上有一个 specific()
方法,也可以调用该方法来检索该查询集中所有页面的特定版本。
最后,请注意在页面或查询集上调用 specific
将导致额外的查询,因此请尝试将所有 specific
调用组合在一起。例如,而不是做:
for page in pages:
specific_page = page.specific # This will result to N extra queries (!)
# do something with specific_page
做一个
for specigic_page in pages.specific(): # 1 extra query for each page subclass
# do something with specific_page
在首页和搜索页中,我想列出各种不同详细显示的页面。我按照文档写了下面的代码:
from wagtail.wagtailcore.models import Page
from my.models import ArticlePage, GalleryPage, VideoPage, SharedLinkPage
PAGE_TYPES = (ArticlePage, GalleryPage, VideoPage, SharedLinkPage,)
class HomePage(Page):
subpage_types = list(PAGE_TYPES)
def get_context(self, request):
context = super(HomePage, self).get_context(request)
context['posts'] = Page.objects.type(PAGE_TYPES).live()
context['recent_posts'] = Page.objects.type(PAGE_TYPES).live()
return context
这样的话,我只能得到[<Page: 1>, <Page:2>]
,我真正想要的是[<ArticlePage: 1>, <GalleryPage:2>]
。
我的问题在搜索页面中是相同的,但使用 search
查询:
Page.search('something', ArticlePage)
会更好:
search_backend.search('something').types(PAGE_TYPES).live()
您应该使用 specific
属性来获取每个页面的最具体的子类形式:
此外,PageQuerySet
上有一个 specific()
方法,也可以调用该方法来检索该查询集中所有页面的特定版本。
最后,请注意在页面或查询集上调用 specific
将导致额外的查询,因此请尝试将所有 specific
调用组合在一起。例如,而不是做:
for page in pages: specific_page = page.specific # This will result to N extra queries (!) # do something with specific_page
做一个
for specigic_page in pages.specific(): # 1 extra query for each page subclass # do something with specific_page