1
0
mirror of https://github.com/django/django.git synced 2024-12-26 11:06:07 +00:00
django/docs/ref/contrib/postgres/expressions.txt
Carlton Gibson b784768eef [4.2.x] Refs #34140 -- Applied rst code-block to non-Python examples.
Thanks to J.V. Zammit, Paolo Melchiorre, and Mariusz Felisiak for
reviews.

Backport of 534ac48297 from main.
2023-02-10 21:12:06 +01:00

38 lines
1.4 KiB
Plaintext

=====================================
PostgreSQL specific query expressions
=====================================
.. module:: django.contrib.postgres.expressions
:synopsis: PostgreSQL specific query expressions
These expressions are available from the
``django.contrib.postgres.expressions`` module.
``ArraySubquery()`` expressions
===============================
.. class:: ArraySubquery(queryset)
``ArraySubquery`` is a :class:`~django.db.models.Subquery` that uses the
PostgreSQL ``ARRAY`` constructor to build a list of values from the queryset,
which must use :meth:`.QuerySet.values` to return only a single column.
This class differs from :class:`~django.contrib.postgres.aggregates.ArrayAgg`
in the way that it does not act as an aggregate function and does not require
an SQL ``GROUP BY`` clause to build the list of values.
For example, if you want to annotate all related books to an author as JSON
objects:
.. code-block:: 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}]