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


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:



echo "Exporting database..." &&\
python 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:

echo 'Rebuilding db...' &&\
python reset $APP &&\
python 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.