blog: Quick Django Tip: Safe and easy database data conversion
One thing that you may find yourself doing is migrating your old projects to Django. Sometimes, this can be fairly complex but if it’s a case of moving data from an old database to your Django models it’s pretty simple.
In this example, I am taking data from a mySQL database that held data for a PHP application and converting it to Django models. What I do is run the data through a ModelForm so that I can test for validation:
# We use the MySQLdb module to connect to a different database to get our old data.
db = MySQLdb.connect(user="me", passwd="password", db="mydatabase")
c = db.cursor(DictCursor)</code>
c.execute("SELECT field1, field2, FROM some_table")
rows = c.fetchall()
for r in rows:
form = AddItemForm(r)
if form.is_valid():
obj = Item(**form.cleaned_data)
obj.save()
else:
# You probably want to log here instead of using print
# form.errors will contain the errors, which you can log as well.
print("Could not add Item %s" % r['field1'])
And that’s it! This is of course a very crude and simple example but it gets the job done and I find it much better then simply passing in data to my model. With the form, it allows me to catch the errors that the end-user may hit when they actually use the form in the application so it’s a win-win.