Last active
January 18, 2018 11:08
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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