# Page QuerySet 参考

所有继承 [`AbstractPage`](../models.html.md#wagtail.models.AbstractPage) 的模型，其 `.objects` 属性都会额外提供一些 QuerySet 方法。

## 示例

### 只选出线上页面

```python
live_pages = Page.objects.live()
```

### 选出 events_index 的后代中已发布的 EventPage

```python
events = EventPage.objects.live().descendant_of(events_index)
```

### 获取菜单项列表

```python
# 这会得到一个 QuerySet，包含首页的线上子页面中设置了 ``show_in_menus`` 的那些
menu_items = homepage.get_children().live().in_menu()
```

## 参考

### *class* wagtail.query.PageQuerySet(\*args, \*\*kwargs)

#### live()

This filters the QuerySet to only contain published pages.

示例：

```python
published_pages = Page.objects.live()
```

#### not_live()

This filters the QuerySet to only contain unpublished pages.

示例：

```python
unpublished_pages = Page.objects.not_live()
```

#### in_menu()

This filters the QuerySet to only contain pages that are in the menus.

示例：

```python
# 用首页的线上子页面构建一个菜单
menu_items = homepage.get_children().live().in_menu()
```

#### NOTE
要把页面放进菜单，请把 show_in_menus 标志设为 true：

```python
# 把 'my_page' 加入菜单
my_page.show_in_menus = True
```

#### not_in_menu()

This filters the QuerySet to only contain pages that are not in the menus.

#### in_site(site)

This filters the QuerySet to only contain pages within the specified site.

示例：

```python
# 获取当前站点中的所有 EventPage
site = Site.find_for_request(request)
site_events = EventPage.objects.in_site(site)
```

#### page(other)

This filters the QuerySet so it only contains the specified page.

示例：

```python
# 往 QuerySet 中追加一个额外页面
new_queryset = old_queryset | Page.objects.page(page_to_add)
```

#### not_page(other)

This filters the QuerySet so it doesn't contain the specified page.

示例：

```python
# 从 QuerySet 中移除一个页面
new_queryset = old_queryset & Page.objects.not_page(page_to_remove)
```

#### descendant_of(other, inclusive=False)

This filters the QuerySet to only contain pages that descend from the specified page.

If inclusive is set to True, it will also contain the page itself (instead of just its descendants).

示例：

```python
# 获取 special_events 页面下的 EventPage
special_events = EventPage.objects.descendant_of(special_events_index)

# 另一种方式
special_events = special_events_index.get_descendants()
```

#### not_descendant_of(other, inclusive=False)

This filters the QuerySet to not contain any pages that descend from the specified page.

If inclusive is set to True, it will also exclude the specified page.

示例：

```python
# 获取不在 archived_events 页面下的 EventPage
non_archived_events = EventPage.objects.not_descendant_of(archived_events_index)
```

#### child_of(other)

This filters the QuerySet to only contain pages that are direct children of the specified page.

示例：

```python
# 获取各栏目列表
sections = Page.objects.child_of(homepage)

# 另一种方式
sections = homepage.get_children()
```

#### not_child_of(other)

This filters the QuerySet to not contain any pages that are direct children of the specified page.

#### ancestor_of(other, inclusive=False)

This filters the QuerySet to only contain pages that are ancestors of the specified page.

If inclusive is set to True, it will also include the specified page.

示例：

```python
# 获取当前栏目
current_section = Page.objects.ancestor_of(current_page).child_of(homepage).first()

# 另一种方式
current_section = current_page.get_ancestors().child_of(homepage).first()
```

#### not_ancestor_of(other, inclusive=False)

This filters the QuerySet to not contain any pages that are ancestors of the specified page.

If inclusive is set to True, it will also exclude the specified page.

示例：

```python
# 获取其他栏目
other_sections = Page.objects.not_ancestor_of(current_page).child_of(homepage)
```

#### parent_of(other)

This filters the QuerySet to only contain the parent of the specified page.

#### not_parent_of(other)

This filters the QuerySet to exclude the parent of the specified page.

#### sibling_of(other, inclusive=True)

This filters the QuerySet to only contain pages that are siblings of the specified page.

By default, inclusive is set to True so it will include the specified page in the results.

If inclusive is set to False, the page will be excluded from the results.

示例：

```python
# 获取兄弟页面列表
siblings = Page.objects.sibling_of(current_page)

# 另一种方式
siblings = current_page.get_siblings()
```

#### not_sibling_of(other, inclusive=True)

This filters the QuerySet to not contain any pages that are siblings of the specified page.

By default, inclusive is set to True so it will exclude the specified page from the results.

If inclusive is set to False, the page will be included in the results.

#### public()

Filters the QuerySet to only contain pages that are not in a private
section and their descendants.

参见：[私有页面](../../advanced_topics/privacy.html.md#private-pages)

#### NOTE
这不会过滤掉未发布的页面。如果你只想得到已发布的公开页面，请使用 `.live().public()`

示例：

```python
# 找出所有公众可查看的页面
all_pages = Page.objects.live().public()
```

#### not_public()

Filters the QuerySet to only contain pages that are in a private
section and their descendants.

#### private()

Filters the QuerySet to only contain pages that are in a private
section and their descendants.

#### search(query, fields=None, operator=None, order_by_relevance=True, order_by=None, backend='default')

This runs a search query on all the items in the QuerySet

参见：[搜索 QuerySet](../../topics/search/searching.html.md#wagtailsearch-searching-pages)

示例：

```python
# 搜索未来的事件
results = EventPage.objects.live().filter(date__gt=timezone.now()).search("Hello")
```

#### type(\*types)

This filters the QuerySet to only contain pages that are an instance
of the specified model(s) (including subclasses).

示例：

```python
# 找出所有属于 AbstractEmailForm 类型或其子类的页面
form_pages = Page.objects.type(AbstractEmailForm)

# 找出所有属于 AbstractEmailForm 或 AbstractEventPage 类型或其子类的页面
form_and_event_pages = Page.objects.type(AbstractEmailForm, AbstractEventPage)
```

#### not_type(\*types)

This filters the QuerySet to exclude any pages which are an instance of the specified model(s).

#### exact_type(\*types)

This filters the QuerySet to only contain pages that are an instance of the specified model(s)
(matching the model exactly, not subclasses).

示例：

```python
# 找出所有恰好是 EventPage 类型的页面
event_pages = Page.objects.exact_type(EventPage)

# 找出所有恰好是 EventPage 或 NewsPage 类型的页面
news_and_events_pages = Page.objects.exact_type(EventPage, NewsPage)
```

#### NOTE
如果你只关心某一种类型的页面，用该具体模型的管理器获取 queryset 会更清晰（通常也更高效）。例如：

```python
event_pages = EventPage.objects.all()
```

#### not_exact_type(\*types)

This filters the QuerySet to exclude any pages which are an instance of the specified model(s)
(matching the model exactly, not subclasses).

示例：

```python
# 首先，找出所有新闻和事件页面
news_and_events = Page.objects.type(NewsPage, EventPage)

# 现在排除恰好为 EventPage 或 NewsPage 类型的页面，
# 只剩下更“专业”的类型的实例
specialised_news_and_events = news_and_events.not_exact_type(NewsPage, EventPage)
```

#### unpublish()

This unpublishes all live pages in the QuerySet.

示例：

```python
# 取消发布 current_page 及其所有子页面
Page.objects.descendant_of(current_page, inclusive=True).unpublish()
```

#### specific(defer=False)

This efficiently gets all the specific items for the queryset, using
the minimum number of queries.

When the "defer" keyword argument is set to True, only generic
field values will be loaded and all specific fields will be deferred.

示例：

```python
# 以最少的数据库查询，获取首页所有子页面的
# specific 实例。
homepage.get_children().specific()
```

另见：[`Page.specific`](../models.html.md#wagtail.models.AbstractPage.specific)

#### defer_streamfields()

Apply to a queryset to prevent fetching/decoding of StreamField values on
evaluation. Useful when working with potentially large numbers of results,
where StreamField values are unlikely to be needed. For example, when
generating a sitemap or a long list of page links.

示例：

```python
# 应用到 queryset 上，避免为某个特定模型
# 获取 StreamField 值
EventPage.objects.all().defer_streamfields()

# 或与 specific() 组合使用，避免为所有模型
# 获取 StreamField 值
homepage.get_children().defer_streamfields().specific()
```

#### first_common_ancestor(include_self=False, strict=False)

Find the first ancestor that all pages in this queryset have in common.
For example, consider a page hierarchy like:

```default
- Home/
    - Foo Event Index/
        - Foo Event Page 1/
        - Foo Event Page 2/
    - Bar Event Index/
        - Bar Event Page 1/
        - Bar Event Page 2/
```

The common ancestors for some queries would be:

```python
>>> Page.objects\
...     .type(EventPage)\
...     .first_common_ancestor()
<Page: Home>
>>> Page.objects\
...     .type(EventPage)\
...     .filter(title__contains='Foo')\
...     .first_common_ancestor()
<Page: Foo Event Index>
```

This method tries to be efficient, but if you have millions of pages
scattered across your page tree, it will be slow.

If include_self is True, the ancestor can be one of the pages in the
queryset:

```python
>>> Page.objects\
...     .filter(title__contains='Foo')\
...     .first_common_ancestor()
<Page: Foo Event Index>
>>> Page.objects\
...     .filter(title__exact='Bar Event Index')\
...     .first_common_ancestor()
<Page: Bar Event Index>
```

A few invalid cases exist: when the queryset is empty, when the root
Page is in the queryset and `include_self` is False, and when there
are multiple page trees with no common root (a case Wagtail does not
support). If `strict` is False (the default), then the first root
node is returned in these cases. If `strict` is True, then a
`ObjectDoesNotExist` is raised.

#### select_related(\*fields, for_specific_subqueries: [bool](https://docs.python.org/3/builtins/functions.html#bool) = False)

Overrides Django's native [`select_related()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.select_related)
to allow related objects to be fetched by the subqueries made when a specific
queryset is evaluated.

When `for_specific_subqueries` is `False` (the default), the method functions
exactly like the original method. However, when `True`, `fields` are
**required**, and must match names of ForeignKey fields on all specific models
that might be included in the result (which can include fields inherited from
concrete parents). Unlike when `for_specific_subqueries` is `False`, no
validation is applied to `fields` when the method is called. Rather, that when
the method is called. Instead, that validation is applied for each individual
subquery when the queryset is evaluated. This difference in behaviour should be
taken into account when experimenting with `for_specific_subqueries=True` .

As with Django's native implementation, you chain multiple applications of
`select_related()` with `for_specific_subqueries=True` to progressively add
to the list of fields to be fetched. For example:

```python
# Fetch 'author' when retrieving specific page data
queryset = Page.objects.specific().select_related("author", for_specific_subqueries=True)

# We're rendering cards with images, so fetch the listing image too
queryset = queryset.select_related("listing_image", for_specific_subqueries=True)

# Fetch some key taxonomy data too
queryset = queryset.select_related("topic", "target_audience", for_specific_subqueries=True)
```

As with Django's native implementation, `None` can be supplied in place of
`fields` to negate a previous application of `select_related()`. By default,
this will only work for cases where `select_related()` was called without
`for_specific_subqueries`, or with `for_specific_subqueries=False`. However,
you can use `for_specific_subqueries=True` to negate subquery-specific
applications too. For example:

```python
# Fetch 'author' and 'listing_image' when retrieving specific page data
queryset = Page.objects.specific().select_related(
    "author",
    "listing_image",
    for_specific_subqueries=True
)

# I've changed my mind. Do not fetch any additional data
queryset = queryset.select_related(None, for_specific_subqueries=True)
```

#### prefetch_related(\*lookups, for_specific_subqueries: [bool](https://docs.python.org/3/builtins/functions.html#bool) = False)

Overrides Django's native [`prefetch_related()`](https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.prefetch_related)
implementation to allow related objects to be fetched alongside the subqueries made
when a specific queryset is evaluated.

When `for_specific_subqueries` is `False` (the default), the method functions
exactly like the original method. However, when `True`, `lookups` are
**required**, and must match names of related fields on all specific models that
might be included in the result (which can include relationships inherited from
concrete parents). Unlike when `for_specific_subqueries` is `False`, no
validation is applied to `lookups` when the method is called. Instead, that
validation is applied for each individual subquery when the queryset is
evaluated. This difference in behaviour should be taken into account when
experimenting with `for_specific_subqueries=True`.

As with Django's native implementation, you chain multiple applications of
`prefetch_related()` with `for_specific_subqueries=True` to progressively
add to the list of lookups to be made. For example:

```python
# Fetch 'contributors' when retrieving specific page data
queryset = Page.objects.specific().prefetch_related("contributors", for_specific_subqueries=True)

# We're rendering cards with images, so prefetch listing image renditions too
queryset = queryset.prefetch_related("listing_image__renditions", for_specific_subqueries=True)

# Fetch some key taxonomy data also
queryset = queryset.prefetch_related("tags", for_specific_subqueries=True)
```

As with Django's native implementation, `None` can be supplied in place of
`lookups` to negate a previous application of `prefetch_related()`. By default,
this will only work for cases where `prefetch_related()` was called without
`for_specific_subqueries`, or with `for_specific_subqueries=False`. However,
you can use `for_specific_subqueries=True` to negate subquery-specific
applications too. For example:

```python
# Fetch 'contributors' and 'listing_image' renditions when retrieving specific page data
queryset = Page.objects.specific().prefetch_related(
    "contributors",
    "listing_image__renditions",
    for_specific_subqueries=True
)

# I've changed my mind. Do not make any additional queries
queryset = queryset.prefetch_related(None, for_specific_subqueries=True)
```

#### NOTE
通常使用 `prefetch_related()` 会为每个提供的 `lookups` 额外执行一次数据库查询。
不过当它与 `for_specific_subqueries=True` 组合时，这个额外查询数
会按结果中的每种具体类型成倍增加。如果你只获取
少量对象，或者结果的类型差异很可能很大，
那么执行这些额外查询带来的额外开销实际上可能对性能
产生负面影响。

把 `prefetch_related()` 与 `for_specific_subqueries=True` 一起使用，应当保留
给需要大量结果的场合，或者类型差异
在某种程度上受限的场合。例如，在渲染子页面列表时，
父页面上设置了 `allow_subtypes`，把结果限制在少量
页面类型上。或者，已经应用了 `type()` 或 `not_type()` 过滤，
把 queryset 限制在少量具体类型上。
