Django Wagtail:在 Django 常规视图中使用自定义方法获取页面的子项

Django Wagtail: get children of page using custom method in django regular view

我正在玩 Wagtail 2.6.1,我遇到了令人困惑的问题。我需要在 vanilla Django 视图中使用 Page 模型。我想获得 BlogPage 的子页面,所以我制作了自定义方法,该方法应该 return 所有子页面。方法有效,但仅在模板视图中有效。当我在 Django 视图中访问它时,它 return 是空查询集。我真的不明白为什么。

我的models.py

class BlogPage(Page):
    template = "blog/blog.html"
    max_count = 1    
    subpage_types = ['blog.BlogPostPage','blog.PostAdvancedPage']        

    promote_panels = Page.promote_panels + [
       FieldPanel('menu_order'),
   ]

    def getChildren(self):
        children = self.get_children().live().all()        
        return children

    def get_context(self, request):
        context = super(BlogPage, self).get_context(request)
        context['categories'] = BlogCategory.objects.order_by('name').all() 
        context['blog_posts'] = self.get_children().live().order_by('-first_published_at').all()            
        return context

    class Meta:
        verbose_name = "Blog"
        verbose_name_plural = "Blogs"

我的views.py

from .models import BlogPage

def post_filter(request):
    if request.method == 'POST':      

        posts = BlogPage().getChildren() # this return empty queryset
        print (posts)

但是当我在模板 blog.html 中渲染这个方法时它起作用了:

<div class="section py-9">
  {{self.getChildren}}
</div>

它成功呈现了模板中的所有子页面:

<PageQuerySet [<Page: Lorem Ipsum 01>,<Page: Lorem Ipsum 02>]>

请注意,我通常使用 get_context 方法在我的模板中呈现所有帖子,我只是尝试在模板中呈现此方法 (getChildren) 以检查它是否有效。

BlogPage().getChildren() 表示 "create a new BlogPage instance in memory, and fetch its children"。自然地,因为它刚刚被创建,它不会有任何子页面,所以这个 returns 一个空的查询集。

要让 post_filter 视图执行一些有用的操作,您需要指定一个现有的 BlogPage 实例,以便它调用 getChildren。你没有提到 post_filter 将如何使用,所以我不知道这些信息应该从哪里来 - 但一种可能是将它作为参数传递给 URL,其中案例 post_filter 将如下所示:

def post_filter(request, page_id):
    if request.method == 'POST':
        posts = BlogPage.objects.get(id=page_id).getChildren()
        print (posts)