python - How can I export an instance and all its related objects in Django? -
someone accidentally deleted instance , related object (through django admin) in production. have backup of database, can data back, script rather copy data, since includes a lot of related objects.
i retrieve item has been deleted (i have model , pk, can mymodel.objects.get(pk=123456)), related objects (foreignkey, manytomany...) in way re-import them in production database.
it can either in sql or serialized format, use loaddata. how can that?
to achieve that, need combine collection of related objects , their serialization. since know exact model instance have been deleted, can first objects deleted (the same way django admin does, nestedobjects collector) , iterating on list generate json.
the more appropriate one-time script (note sept 2016: updated django >= 1.9):
from itertools import chain django.core import serializers django.contrib.admin.utils import nestedobjects 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())) open("backup_export.json", "w") f: f.write(serializers.serialize("json", objects)) this produce json file instances have been deleted. can use manage.py loaddata put them on production database. when re-importing json, should deactivate post_save signal, otherwise can failed complex dependencies.
Comments
Post a Comment