2
0

expressions.txt 1.4 KB

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