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 2 years, 9 months ago
  2. Admin action for a generic "CSV Export" by javinievas 1 year, 2 months ago
  3. Generic admin action export selected rows to excel by jordic 7 months, 3 weeks ago
  4. render_to_json by marinho 4 years, 6 months ago
  5. Memento by manelvf 1 year, 4 months ago

Comments

(Forgotten your password?)