File: expressions.txt

package info (click to toggle)
python-django 3%3A5.2.5-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 61,236 kB
  • sloc: python: 361,585; javascript: 19,250; xml: 211; makefile: 182; sh: 28
file content (37 lines) | stat: -rw-r--r-- 1,442 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
=====================================
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}]