Django workflow when modifying models frequently?

那年仲夏 提交于 2019-11-29 19:45:31

Steps 2 & 3 can be done in one step:

manage.py reset appname

Step 4 is most easily managed, from my understanding, by using fixtures

This is a job for Django's fixtures. They are convenient because they are database independent and the test harness (and manage.py) have built-in support for them.

To use them:

  1. Set up your data in your app (call it "foo") using the admin tool
  2. Create a fixtures directory in your "foo" app directory
  3. Type: python manage.py dumpdata --indent=4 foo > foo/fixtures/foo.json

Now, after your syncdb stage, you just type:

 python manage.py loaddata foo.json

And your data will be re-created.

If you want them in a test case:

class FooTests(TestCase):
    fixtures = ['foo.json']

Note that you will have to recreate or manually update your fixtures if your schema changes drastically.

You can read more about fixtures in the django docs for Fixture Loading

Here's what we do.

  1. Apps are named with a Schema version number. appa_2, appb_1, etc.

  2. Minor changes don't change the number.

  3. Major changes increment the number. Syncdb works. And a "data migration" script can be written.

    def migrate_appa_2_to_3():
        for a in appa_2.SomeThing.objects.all():
            appa_3.AnotherThing.create( a.this, a.that )
            appa_3.NewThing.create( a.another, a.yetAnother )
        for b in ...
    

The point is that drop and recreate isn't always appropriate. It's sometimes helpful to move data form the old model to the new model without rebuilding from scratch.

South is the coolest.

Though good ol' reset works best when data doesn't matter.

http://south.aeracode.org/

To add to Matthew's response, I often also use custom SQL to provide initial data as documented here.

Django just looks for files in <app>/sql/<modelname>.sql and runs them after creating tables during syncdb or sqlreset. I use custom SQL when I need to do something like populate my Django tables from other non-Django database tables.

Personally my development db is for a project I'm working on right now is rather large, so I use dmigrations to create db migration scripts to modify the db (rather than wiping out the db everytime like I did in the beginning).

Edit: Actually, I'm using South now :-)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!