Altering database tables in Django

前端 未结 7 1385
野性不改
野性不改 2020-12-07 11:33

I\'m considering using Django for a project I\'m starting (fyi, a browser-based game) and one of the features I\'m liking the most is using syncdb to automatica

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-07 11:43

    One good way to do this is via fixtures, particularly the initial_data fixtures.

    A fixture is a collection of files that contain the serialized contents of the database. So it's like having a backup of the database but as it's something Django is aware of it's easier to use and will have additional benefits when you come to do things like unit testing.

    You can create a fixture from the data currently in your DB using django-admin.py dumpdata. By default the data is in JSON format, but other options such as XML are available. A good place to store fixtures is a fixtures sub-directory of your application directories.

    You can load a fixure using django-admin.py loaddata but more significantly, if your fixture has a name like initial_data.json it will be automatically loaded when you do a syncdb, saving the trouble of importing it yourself.

    Another benefit is that when you run manage.py test to run your Unit Tests the temporary test database will also have the Initial Data Fixture loaded.

    Of course, this will work when when you're adding attributes to models and columns to the DB. If you drop a column from the Database you'll need to update your fixture to remove the data for that column which might not be straightforward.

    This works best when doing lots of little database changes during development. For updating production DBs a manually generated SQL script can often work best.

提交回复
热议问题