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. Dynamically create Django admin actions by pantsman 3 years, 5 months ago
  2. Generic admin action export selected rows to excel by aemb87 7 months, 1 week ago
  3. Generic admin action export selected rows to excel by jordic 1 year, 7 months ago
  4. Generic csv export admin action by dek 3 years, 9 months ago
  5. Generic CSV export admin action factory with relationship spanning fields and labels by blackrobot 5 months ago

Comments

(Forgotten your password?)