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
fromdjango.db.modelsimportSubquery,JSONFieldclassPostgresqlJsonField(JSONField):deffrom_db_value(self,value,expression,connection):returnvalueclassSubqueryJson(Subquery):""" A replacement for select_related, that allows to fetch row of linked data as a subquery """template="(SELECT row_to_json(_subquery) FROM (%(subquery)s) _subquery)"output_field=PostgresqlJsonField()classSubqueryJsonAgg(Subquery):""" A replacement for prefetch_related, that allows to fetch array of linked data as a subquery """template="(SELECT array_to_json(coalesce(array_agg(row_to_json(_subquery)), array[]::json[])) FROM (%(subquery)s) _subquery)"output_field=PostgresqlJsonField()
Comments
Please login first before commenting.