Export Related as JSON Admin Action

 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 4 years, 7 months ago
  2. Admin action for a generic "CSV Export" by javinievas 3 years, 1 month ago
  3. Generic admin action to export data into excel/csv by vinay.chittora 8 months, 2 weeks ago
  4. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 1 year, 3 months ago
  5. Generic admin action export selected rows to excel by jordic 2 years, 6 months ago

Comments

(Forgotten your password?)