Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django initialize database in a custom way when syncdb

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?

like image 232
Mike Lee Avatar asked Nov 29 '25 21:11

Mike Lee


1 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.

like image 174
Burhan Khalid Avatar answered Dec 02 '25 13:12

Burhan Khalid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!