Skip to content

Instantly share code, notes, and snippets.

Created September 20, 2017 21:57
Show Gist options
  • Save anonymous/7f1dd2b910d98b83bcfb8882ff793163 to your computer and use it in GitHub Desktop.
Save anonymous/7f1dd2b910d98b83bcfb8882ff793163 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
# parcours des objets concernés
obj = Company.objects.get(pk=XX)
collector = NestedObjects(using=DEFAULT_DB_ALIAS)
collector.collect([obj])
datas = collector.nested()
data = flatten(datas[1])
# serialisation
with open("export_xx.xml", "w") as out:
xml_serializer.serialize(data, 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