I'm using Django in a development process. It is annoying that every time I change a bit in a model I need to delete database and run syncdb. For the purpose of testing, I want to add some initial data into database automatically every time when I run syncdb. I've tried put these sort of code inside one app's __init__.py, but it would run before database created and it's a bit annoying to deal with exceptions. Isn't there a neater way to do this?
2 Answers
Once you have initially populated the database; use the dumpdata command to create a fixture (a copy of data). Save it to a file. Then use the loaddata command to automatically populate the database.
Suppose you have an app called bookstore for which you want to automatically load a series of books, authors, etc.
Once you have added some records in the database:
python django-admin.py dumpdata bookstore > initial.json
Once you have made some changes or want to recreate the database:
python django-admin.py loaddata initial.json
South is nice, but it is overkill for this purpose.
1 Comment
If you need to make changes in database and you want that your data remains safe then SOUTH is the right software for you.
It manages change in database and its data. You wont need to delete database when you make changes if you have South. Also it has backups of previous states of database so that if you want to revert back you can. I recommend you read its documentation. It will surely help.
loaddatadocs.djangoproject.com/en/dev/ref/django-admin/…