Debian Codegraph @

docs/ref/contrib/postgres/expressions.txt

raw
1 =====================================
2 PostgreSQL specific query expressions
3 =====================================
4
5 .. module:: django.contrib.postgres.expressions
6 :synopsis: PostgreSQL specific query expressions
7
8 These expressions are available from the
9 ``django.contrib.postgres.expressions`` module.
10
11 ``ArraySubquery()`` expressions
12 ===============================
13
14 .. class:: ArraySubquery(queryset)
15
16 ``ArraySubquery`` is a :class:`~django.db.models.Subquery` that uses the
17 PostgreSQL ``ARRAY`` constructor to build a list of values from the queryset,
18 which must use :meth:`.QuerySet.values` to return only a single column.
19
20 This class differs from :class:`~django.contrib.postgres.aggregates.ArrayAgg`
21 in the way that it does not act as an aggregate function and does not require
22 an SQL ``GROUP BY`` clause to build the list of values.
23
24 For example, if you want to annotate all related books to an author as JSON
25 objects:
26
27 .. code-block:: pycon
28
29 >>> from django.db.models import OuterRef
30 >>> from django.db.models.functions import JSONObject
31 >>> from django.contrib.postgres.expressions import ArraySubquery
32 >>> books = Book.objects.filter(author=OuterRef("pk")).values(
33 ... json=JSONObject(title="title", pages="pages")
34 ... )
35 >>> author = Author.objects.annotate(books=ArraySubquery(books)).first()
36 >>> author.books
37 [{'title': 'Solaris', 'pages': 204}, {'title': 'The Cyberiad', 'pages': 295}]