Skip to content

Instantly share code, notes, and snippets.

@vparitskiy
Last active January 18, 2018 11:08
Show Gist options
  • Save vparitskiy/37751968dc7542c8186b40fc4015bda9 to your computer and use it in GitHub Desktop.
Save vparitskiy/37751968dc7542c8186b40fc4015bda9 to your computer and use it in GitHub Desktop.
Dumps cascade deleted items to fixtures. Can be used to restore accidentally deleted item from the backup
from __future__ import unicode_literals
from django.apps import apps
from django.contrib.admin.utils import NestedObjects
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.utils.encoding import force_unicode
def restore(model, pk, srl_format='json'):
try:
model = apps.get_model(model)
except LookupError:
print 'Model "{}" does not exist'.format(force_unicode(model))
return
try:
instance = model._default_manager.get(pk=pk)
except ObjectDoesNotExist:
print 'Object with pk {} does not exist'.format(force_unicode(pk))
return
collector = NestedObjects(using='default')
collector.collect([instance])
for cls, objects in collector.data.iteritems():
opts = cls._meta.app_label, cls.__name__.lower()
filename = '{}_{}.json'.format(*opts)
with open(filename, b'w') as f:
f.write(
serializers.serialize(srl_format, objects)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment