Skip to content

Instantly share code, notes, and snippets.

@martinsam
Forked from anonymous/reverse_delete_dj_object.py
Last active September 21, 2017 08:03
Show Gist options
  • Save martinsam/9bbc8fcf6da222e40b074665cb4482c5 to your computer and use it in GitHub Desktop.
Save martinsam/9bbc8fcf6da222e40b074665cb4482c5 to your computer and use it in GitHub Desktop.
Récupérer les données suite à une suppression d'objet
from django.contrib.admin.util import NestedObjects
from django.db import DEFAULT_DB_ALIAS
from django.core import serializers
# flatten function
def flatten(xs):
result = []
if isinstance(xs, (list, tuple)):
for x in xs:
result.extend(flatten(x))
else:
result.append(xs)
return result
perms = Permission.objects.filter(content_type__id=16, subscription_id=19663)
# parcours des objets concernés
obj = Company.objects.get(pk=19663)
collector = NestedObjects(using=DEFAULT_DB_ALIAS)
collector.collect([obj])
datas = collector.nested()
data = flatten(datas[1])
# serialisation
XMLSerializer = serializers.get_serializer("xml")
xml_serializer = XMLSerializer()
with open("company_19663.xml", "w") as out:
xml_serializer.serialize(data+[datas[0]]+list(perms), stream=out)
# deserialisation
file = open("your_file.py", "r")
data = file.read()
for obj in serializers.deserialize("xml", data):
obj.save()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment