Django: Preserve table data when changing model (adding fields)

Overview

Django, out-of-the-box doesn’t knows how to add rows to your db when the model changed, You have 2 options:

  1. manually add the field to the db. (I won’t demonstrate this)
  2. export data > reset your db > import data.

Export > Reset > Import

Most of the time, Django will find errors after you’ll change the model, so the problem is, you can’t export the data after you’ve changed your model. you need to export it. edit your model and then reset+import.

use those bash scripts:

Export

DB=/var/www/django/db
APP=myapp

echo "Exporting database..." &&\
python manage.py dumpdata $APP --format='json' --indent=4 --verbosity=1 > backup/DUMP.json &&\
echo 'Backing up db file...' &&\
cp $DB $DB.bk

Reset & Import

Now, update your model with the new fields and run the following:

DB=/var/www/django/db
APP=myapp
echo 'Rebuilding db...' &&\
python manage.py reset $APP &&\
python manage.py loaddata backup/DUMP.json

 

Leave a Reply

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

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.