#### 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
South documentation [contains a description](http://south.readthedocs.org/en/0.7.6/fixtures.html#fixtures-from-migrations) of the way you can load fixtures inside the data-migrations.
def forwards(self, orm):
from django.core.management import call_command
call_command("loaddata", "my_fixture.json")
It seems pretty clear and easy, but in fact it does not work the way you expect from south migrations, because the fixture loading does not engage the **orm** object. So, it allows **loaddata** management command to use standard models loading mechanism, and it would provide the most recent version of the models, obviously, which may not correspond to the schema of the fixture`s data.
To be ensured that migration will use appropriate version of the models for fixture loading you could use code like follows:
class Migration(DataMigration):
def forwards(self, orm):
load_fixture('my_fixture.json', orm)
class Migration(DataMigration):
def forwards(self, orm):
with southern_models(orm):
call_command("loaddata", "my_fixture.json")
- fixtures
- migration
- fixture
- south
- datamigration