How to perform a one-off migration into Django ORM

While working on a project I haven’t yet made public, I found myself needing to migrate data into a Django project without being able to use the simple, common “Use inspectdb, then migrate to the new form with South” approach some suggest.

Here’s the simplest sequence of commands I’ve found for performing a migration to an existing app with some possibility for reusing the migration later if necessary:

django-admin.py startproject <throwaway project>
cd <throwaway project>
python manage.py startapp <real target app name>
[repeat for all target apps]
[edit settings.py and tell it about your DB and apps]
python manage.py inspectdb > temp_models.py
[look at temp_models.py and make any adjustments necessary]
[edit models.py for each app and move the relevant bits from temp_models.py]
python manage.py syncdb
python manage.py dumpdata > migrated_data.json
[...and then set up South to prevent future pain] 

Nothing fancy. Just something that saved me some hassle and might do the same for someone else. Here are the actual commands I used for clarification:

django-admin.py startproject gbi_temp
cd gbi_temp
python manage.py startapp gbindex
python manage.py startapp icolinks
python manage.py startapp ffcms_core
vim settings.py
python manage.py inspectdb > temp_models.py
vim temp_models.py gbindex/models.py icolinks/models.py \
    ffcms_core/models.py
python manage.py syncdb
python manage.py dumpdata > migrated_data.json
mv migrated_data.json ../ffcms/
cd ../ffcms
python manage.py loaddata migrated_data.json

CC BY-SA 4.0 How to perform a one-off migration into Django ORM by Stephan Sokolow is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

This entry was posted in Geek Stuff. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

By submitting a comment here you grant this site a perpetual license to reproduce your words and name/web site in attribution under the same terms as the associated post.       Also, please be aware that non-constructive comments will have their URL field erased before being approved in order to combat SEO spam.