Flickr Badge

Sunday, September 24, 2006

Export django database to an xml file

Here is a simple python script to export your django database to an XML file. I haven't tested it out very thoroughly. It seems to work for the fields that I have in my model - CharField, TextField, DateField, IntegerField, PositiveIntegerField and ForeignKey. If you find any bugs, add a comment to this post.
# setup the environment
import os, sys
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"

class XMLWriter:
"""Helper class to write out an xml file"""
def __init__(self, pretty=True):
"""Set pretty to True if you want an indented XML file"""
self.output = ""
self.stack = []
self.pretty = pretty

def open(self, tag):
"""Add an open tag"""
if self.pretty:
self.output += " "*(len(self.stack) - 1);
self.output += "<" + tag + ">"
if self.pretty:
self.output += "\n"

def close(self):
"""Close the innermost tag"""
if self.pretty:
self.output += "\n" + " "*(len(self.stack) - 1);
tag = self.stack.pop()
self.output += "</" + tag + ">"
if self.pretty:
self.output += "\n"

def closeAll(self):
"""Close all open tags"""
while len(self.stack) > 0:

def content(self, text):
"""Add some content"""
if self.pretty:
self.output += " "*len(self.stack);
self.output += str(text)

def save(self, filename):
"""Save the data to a file"""
fp = open(filename, "w")

import django.db.models

writer = XMLWriter(pretty=False)"djangoexport")
models = django.db.models.get_models()
for model in models:
# model._meta.object_name holds the name of the model + "s")
for item in model.objects.all():
for field in item._meta.fields:
value = getattr(item,
if value != None:
if isinstance(value, django.db.models.base.Model):
# This field is a foreign key, so save the primary key
# of the referring object
pk_name =
pk_value = getattr(value, pk_name)
Note to self: Find a better way to colorize the source code

This post is a part of the selected archive.


Anonymous said...

Looks great! Now we just need a similar script to read one of these XML files and update the items in a database. Then we'd have a very easy way to backup/restore databases. Nice work.

Siddhi said...

Thanks. The backup/restore idea is a great one. I think I'll work on the import script over the weekend.

Chris Bloom said...

Just wanted to let you know this script was still helpful some 9 years later. Had to make a few small tweaks, but I just used it to export some Django 2.7 content so I could import it elsewhere. Thanks!