What is the difference between ChildPage.objects.child_of(self) and ParentPage.get_children()?

六月ゝ 毕业季﹏ 提交于 2021-01-29 15:21:14

问题


I think that ChildPage.objects.child_of(self) and ParentPage.get_children() produce same result because subpage_types of ParentPage is just one ['ChildPage'].

But when I try to filter the result of ParentPage.get_children() there is an error.

    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

Traceback (most recent call last):

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

回答1:


With self.get_children(), the page type of the child pages is not known in advance - a page's children may include multiple different types. Since Django querysets don't (as standard*) support combining data from multiple models, the results are returned as the basic Page type, which just contains the core fields common to all pages such as the title and slug. Filtering on tags therefore fails, because that field does not exist on the Page model.

With ChildPage.objects.child_of(self), Django knows in advance that the page type is ChildPage - if self had any child pages of other types - they would not be included in the results - so it can query directly on the ChildPage table, and consequently all fields of ChildPage (including tags) are available for filtering.

* Wagtail does provide a specific() method on the queryset to pull in the full data of the pages, but this is implemented as a postprocessing step after the main database query is done, so this still won't allow you to filter on fields that aren't part of the base Page model.



来源:https://stackoverflow.com/questions/65698455/what-is-the-difference-between-childpage-objects-child-ofself-and-parentpage-g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!