- Author:
- johnboxall
- Posted:
- July 2, 2009
- Language:
- Python
- Version:
- 1.0
- 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
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Please login first before commenting.