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. .. versionadded:: 4.0
    
  17. 
    
  18. ``ArraySubquery`` is a :class:`~django.db.models.Subquery` that uses the
    
  19. PostgreSQL ``ARRAY`` constructor to build a list of values from the queryset,
    
  20. which must use :meth:`.QuerySet.values` to return only a single column.
    
  21. 
    
  22. This class differs from :class:`~django.contrib.postgres.aggregates.ArrayAgg`
    
  23. in the way that it does not act as an aggregate function and does not require
    
  24. an SQL ``GROUP BY`` clause to build the list of values.
    
  25. 
    
  26. For example, if you want to annotate all related books to an author as JSON
    
  27. objects::
    
  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}]