Login

Export Related as JSON Admin Action

Author:
johnboxall
Posted:
July 2, 2009
Language:
Python
Version:
1.0
Tags:
serialize admin json export admin-action
Score:
2 (after 2 ratings)

The Django Admin Action documentation leads you through exporting a queryset to JSON. However exporting from a single model rarely tells the whole story.

Using the CollectObjects class, export_related_as_json gathers all instances related by foreign keys to what is being exported and exports them as well in a serialization bonanza.

Use it to export Users and you'll get their Profile objects as well!

Usage

# admin.py
from django.contrib import admin

admin.site.add_action(export_related_as_json)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.core import serializers
from django.db.models.query import CollectedObjects
from django.http import HttpResponse

def export_related_as_json(modeladmin, request, qs):
    """Serializes the selected queryset and all related objects to JSON"""
    response = HttpResponse(mimetype="text/javascript")
    
    # Gather the related objects for each instance in the queryset.
    collected_objs = CollectedObjects()
    for obj in qs:
        obj._collect_sub_objects(collected_objs)
    
    # Collect all the instances into a list suitable for serialization.
    objs = []
    for _, objs_dict in collected_objs.items():  # co doesn't implement values
        objs += objs_dict.values()
        
    serializers.serialize("json", objs, stream=response, indent=4)    
    return response

More like this

  1. Generic csv export admin action by dek 5 years, 11 months ago
  2. Admin action for a generic "CSV Export" by javinievas 4 years, 5 months ago
  3. Admin action for a "CSV Export" with ManyToManyField by CarlosRodriguez 1 year, 1 month ago
  4. Generic admin action to export data into excel/csv by vinay.chittora 2 years ago
  5. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 2 years, 7 months ago

Comments

Please login first before commenting.