#### Allows to fetch a row or array of rows of data, linked to parent object, in a single query. Data is fetched as JSON and is not serialized into Django objects.
##### Example:
from django.db import Models
class Book(models.Model):
authors = models.ManyToMany('Author', through='BookToAuthor', blank=True)
title = models.CharField(max_length=512, default='')
class Author(models.Model):
name = models.CharField(max_length=512, default='')
class BookToAuthor(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
book = models.ForeignKey(Book, on_delete=models.CASCADE)
##### Download author with all his/her books in a single query
from django.db.models import OuterRef
books_by_author_subquery = Book.objects.filter(
id__in=BookToAuthor.objects.filter(author_id=OuterRef(OuterRef('id')))
).values('title')
author = Author.objects\
.annotate(books=SubqueryJsonAgg(books_by_author_subquery))\
.get(id=1)
- json
- postgres
- postgresql
- subquery