Skip to content

Instantly share code, notes, and snippets.

@baxeico
Forked from alexhayes/dumpnested.py
Created April 8, 2024 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baxeico/6872a4707bac151aa49d92188d6b216a to your computer and use it in GitHub Desktop.
Save baxeico/6872a4707bac151aa49d92188d6b216a to your computer and use it in GitHub Desktop.
Django management command to dump objects to JSON with all nested relations included.
"""
Dump out objects and all nested associations.
"""
import sys
from django.apps import apps
from django.contrib.admin.utils import NestedObjects
from django.core import serializers
from django.core.management import BaseCommand
from django.db import router
from django.db.models import Model
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args', metavar='[app_label.ModelName.id1,id2,id3...]', nargs='*',
help='Specify assessments by their ID.')
parser.add_argument('--indent', default=None, dest='indent', type=int,
help='Specifies the indent level to use when pretty-printing output.')
def handle(self, *args, **options):
indent = options.get('indent')
self.items = []
for arg in args:
app_label, model, ids = arg.split('.')
app_config = apps.get_app_config(app_label)
Model = app_config.get_model(model)
for id in ids.split(','):
self.dump_object(Model.objects.filter(pk=id))
serializers.serialize('json',
self.items,
indent=indent,
stream=sys.stdout)
def dump_object(self, obj):
using = router.db_for_write(obj.__class__)
collector = NestedObjects(using=using)
collector.collect(obj)
objs = collector.nested(lambda x: x)
objs = list(zip(objs[::2], objs[1::2]))
self.get_objects(objs)
def get_objects(self, item):
if isinstance(item, Model):
self.items.append(item)
elif isinstance(item[0], Model):
for _item in item:
self.get_objects(_item)
else:
for obj, children in item:
self.items.append(obj)
# items.append(obj)
self.get_objects(children)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment