ChildPage.objects.child_of(self) 和 ParentPage.get_children() 有什么区别? 回溯最近一次调用最后一次:

问题描述

我认为 ChildPage.objects.child_of(self)ParentPage.get_children() 产生相同的结果,因为 ParentPagesubpage_types 只是一个 ['ChildPage']

但是当我尝试过滤 ParentPage.get_children() 的结果时出现错误

    def get_context(self,request,*args,**kwargs):
        context = super().get_context(request,**kwargs)

        child = self.get_children().live().public()               # <- don't works
        child = ChildPage.objects.child_of(self).live().public()  # <- works

        if request.GET.get('tag',None):
            tags = request.GET.get('tag')
            child = child.filter(tags__slug__in=[tags])  # <- error here

        context["child"] = child
        return context

回溯(最近一次调用最后一次):

Cannot resolve keyword 'tags' into field. Choices are: alias_of,alias_of_id,aliases,blogindexpage,blogpage,content_type,content_type_id,depth,draft_title,expire_at,expired,first_published_at,formsubmission,go_live_at,group_permissions,has_unpublished_changes,homepage,id,last_published_at,latest_revision_created_at,live,live_revision,live_revision_id,locale,locale_id,locked,locked_at,locked_by,locked_by_id,numchild,owner,owner_id,partnerindexpage,partnerpage,path,redirect,revisions,search_description,SEO_title,show_in_menus,sites_rooted_here,slug,title,translation_key,url_path,view_restrictions,workflow_states,workflowpage

解决方法

使用self.get_children(),子页面的页面类型是事先未知的——一个页面的子页面可能包括多种不同的类型。由于 Django 查询集不(作为标准*)支持组合来自多个模型的数据,结果以基本的 Page 类型返回,它只包含所有页面共有的核心字段,如标题和 slug。因此过滤 tags 失败,因为页面模型中不存在该字段。

使用 ChildPage.objects.child_of(self),Django 预先知道页面类型是 ChildPage - 如果 self 有任何其他类型的子页面 - 它们不会包含在结果中 - 所以它可以直接查询ChildPage 表,因此 ChildPage 的所有字段(包括 tags)都可用于过滤。

* Wagtail 确实在查询集上提供了一个 specific() 方法来拉入页面的完整数据,但是这是在主数据库查询完成后作为后处理步骤实现的,所以这仍然不允许您可以在不属于基本页面模型的字段上filter

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...