Here's something I wrote to export database contents from a django application into the Django database API format.
It's certainly not going to do all the work for you - in particular you'll need to reorder things to make sure things that Django wants to be objects (i.e. Foreign Keys) are instantiated before the related object gets made.
Hope this helps someone somewhere.
PYTHON:
-
#!/usr/bin/env python
-
"""
-
Script to export data from a Django database and generate
-
the appropriate django DB-API commands
-
Make sure you run it from the same directory as your settings.py
-
NOTE: it does NOT handle relationships yet, so, you'll need to take the output
-
and hand edit it to make sure that anything that Django needs as an object,
-
gets instantiated first
-
(c) Simon Greenhill / dev@simon.net.nz / http://simon.net.nz
-
Version: 0.00001
-
"""
-
-
debug = False # just a debug flag to spit out what we're doing.
-
-
import sys
-
-
from django.core.management import setup_environ
-
-
try:
-
import settings
-
except ImportError:
-
print "You don't appear to have a settings file in this directory!"
-
print "Please run this from inside a project directory"
-
sys.exit()
-
-
setup_environ(settings)
-
-
from django.db import models
-
-
# do model imports
-
print """
-
###############################################################
-
# #
-
# Model imports #
-
# #
-
###############################################################
-
"""
-
-
for app in models.get_apps():
-
for model in app.models.get_models():
-
print "from %s import %s" % ( app.__name__, model._meta.object_name )
-
-
# what apps we've done
-
seen = []
-
for app in models.get_apps():
-
for model in app.models.get_models():
-
if model not in seen:
-
print
-
print "# %s.%s " % (app.__name__, model._meta.object_name)
-
print
-
-
if debug:
-
print "#\t", model
-
-
for row in model.objects.iterator():
-
-
if debug:
-
print "#\t\t",row
-
-
attrs = []
-
for col in row._meta.fields:
-
key = col.name
-
value = getattr(row, key)
-
if col.get_internal_type() == 'ForeignKey':
-
###print key, 'bork bork bork'
-
pass
-
-
# if it's numeric, we don't need to quote it.
-
if isinstance(value,int) or isinstance(value,float):
-
pass
-
# if it's a string...
-
elif isinstance(value,str):
-
# ... and it's got a quote mark or new line in it, then triple-quote it.
-
if value.find('"')> 0 or value.find("\n")> 0:
-
value = '"""%s"""' % value
-
# ... otherwise single quote it.
-
else:
-
value = '"%s"' % value
-
# don't know what it is, but single quote it
-
else:
-
value = '"%s"' % value
-
-
attrs.append( '%s=%s' % ( key, value ) )
-
-
if debug:
-
print "#\t\t\t", key, getattr(row, key)
-
-
print """%s(%s).save()""" % ( model._meta.object_name, ', '.join(attrs) )
-
-
seen.append(model)
Update 19/01/2007: limodou has written a far superior export solution here.
--Simon