[Fixed]-How can I export an instance and all its related objects in Django?

29πŸ‘

βœ…

To achieve that, you need to combine the collection of related objects and their serialization. Since you know the exact model instance that have been deleted, you can first get all the objects deleted (the same way that the django admin does, with a NestedObjects collector) and then iterating on this list to generate a json.

The more appropriate is to do a one-time script (note Sept 2016: updated for Django >= 1.9):

from itertools import chain      

from django.core import serializers
from django.contrib.admin.utils import NestedObjects

from myproject.myapp.models import MyModel

collector = NestedObjects(using="default") # database name
collector.collect([MyModel.objects.get(pk=123456)])

objects = list(chain.from_iterable(collector.data.values()))
with open("backup_export.json", "w") as f:
    f.write(serializers.serialize("json", objects))

This will produce a json file with all the instances that have been deleted. You can now use manage.py loaddata to put them back on your production database. When re-importing the json, you should deactivate the post_save signal, otherwise it can failed sometimes with complex dependencies.

πŸ‘€Maxime Lorant

Leave a comment