Someone accidentally deleted an instance and all the related object (through the Django admin) in production. I have a backup of the database, so I can get those data back, but I would like to do it with a script rather than copy the data, since it includes a lot of related objects.
I would like to retrieve the item that has been deleted (I do have its model and its pk, so I can do
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 f as open("backup_export.json", "w"): 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.