【问题标题】:What is the difference between ChildPage.objects.child_of(self) and ParentPage.get_children()?ChildPage.objects.child_of(self) 和 ParentPage.get_children() 有什么区别?
【发布时间】:2021-01-13 08:52:01
【问题描述】:

我认为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, *args, **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

【问题讨论】:

    标签: wagtail django-taggit


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-16
      • 2015-10-04
      • 2010-09-14
      相关资源
      最近更新 更多