Skip to content

Instantly share code, notes, and snippets.

@esauro
Created April 25, 2012 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esauro/2490831 to your computer and use it in GitHub Desktop.
Save esauro/2490831 to your computer and use it in GitHub Desktop.
Action to generate a json document with all objects and related objects
# -*- coding: utf-8 -*-
__author__ = 'esauro'
from django.core import serializers
from django.db.models.deletion import Collector
from django.http import HttpResponse
from django.db import router
def export_related_as_json(modeladmin, request, qs):
"""Serializes the selected queryset and all related objects to JSON"""
response = HttpResponse(mimetype="text/plain")
# TODO: This should calculate the database instead of using "default"
collector = Collector(using = router.db_for_read(modeladmin.model))
collector.collect(qs)
serializers.serialize("json",
[o for m,o in collector.instances_with_model()],
stream = response,
indent = 4,
)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment