---
title: "PostgreSQL 特有查询表达式"
version: 5.2
locale: zh-hans
source: https://docs.djangoproject.com/zh-hans/5.2/ref/contrib/postgres/expressions/
canonical: https://djangodocs.dev/zh-hans/5.2/ref/contrib/postgres/expressions/
---
# PostgreSQL 特有查询表达式

这些表达式可以从 `django.contrib.postgres.expressions` 模块中获得。

## `ArraySubquery()` 表达式

#### `class ArraySubquery(queryset)`

`ArraySubquery` 是一个 [`Subquery`](/zh-hans/5.2/ref/models/expressions/#django.db.models.Subquery)，使用 PostgreSQL 的 `ARRAY` 构造函数，从查询集中建立一个值列表，它必须使用 [`QuerySet.values()`](/zh-hans/5.2/ref/models/querysets/#django.db.models.query.QuerySet.values) 来只返回一个列。

这个类与 [`ArrayAgg`](/zh-hans/5.2/ref/contrib/postgres/aggregates/#django.contrib.postgres.aggregates.ArrayAgg) 不同，它不作为一个聚合函数，也不需要一个 SQL `GROUP BY` 子句来建立值的列表。

例如，如果您想要将作者的所有相关书籍注释为 JSON 对象：

```pycon
>>> from django.db.models import OuterRef
>>> from django.db.models.functions import JSONObject
>>> from django.contrib.postgres.expressions import ArraySubquery
>>> books = Book.objects.filter(author=OuterRef("pk")).values(
...     json=JSONObject(title="title", pages="pages")
... )
>>> author = Author.objects.annotate(books=ArraySubquery(books)).first()
>>> author.books
[{'title': 'Solaris', 'pages': 204}, {'title': 'The Cyberiad', 'pages': 295}]
```
