且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将模型从一个 django 应用程序迁移到一个新应用程序中?

更新时间:2023-02-13 08:09:45

如何使用南迁移.

假设我们有两个应用程序:通用和专用:

How to migrate using south.

Lets say we got two apps: common and specific:

myproject/
|-- common
|   |-- migrations
|   |   |-- 0001_initial.py
|   |   `-- 0002_create_cat.py
|   `-- models.py
`-- specific
    |-- migrations
    |   |-- 0001_initial.py
    |   `-- 0002_create_dog.py
    `-- models.py

现在我们要将模型 common.models.cat 移动到特定的应用程序(精确到 specific.models.cat).先对源代码进行修改,然后运行:

Now we want to move model common.models.cat to specific app (precisely to specific.models.cat). First make the changes in the source code and then run:

$ python manage.py schemamigration specific create_cat --auto
 + Added model 'specific.cat'
$ python manage.py schemamigration common drop_cat --auto
 - Deleted model 'common.cat'

myproject/
|-- common
|   |-- migrations
|   |   |-- 0001_initial.py
|   |   |-- 0002_create_cat.py
|   |   `-- 0003_drop_cat.py
|   `-- models.py
`-- specific
    |-- migrations
    |   |-- 0001_initial.py
    |   |-- 0002_create_dog.py
    |   `-- 0003_create_cat.py
    `-- models.py

现在我们需要编辑两个迁移文件:

Now we need to edit both migration files:

#0003_create_cat: replace existing forward and backward code
#to use just one sentence:

def forwards(self, orm):
    db.rename_table('common_cat', 'specific_cat') 

    if not db.dry_run:
        # For permissions to work properly after migrating
        orm['contenttypes.contenttype'].objects.filter(
            app_label='common',
            model='cat',
        ).update(app_label='specific')

def backwards(self, orm):
    db.rename_table('specific_cat', 'common_cat')

    if not db.dry_run:
        # For permissions to work properly after migrating
        orm['contenttypes.contenttype'].objects.filter(
            app_label='specific',
            model='cat',
        ).update(app_label='common')

#0003_drop_cat:replace existing forward and backward code
#to use just one sentence; add dependency:

depends_on = (
    ('specific', '0003_create_cat'),
)
def forwards(self, orm):
    pass
def backwards(self, orm):
    pass

现在两个应用程序迁移都意识到了变化,生活变得少了一点:-)在迁移之间设置这种关系是成功的关键.现在如果你这样做:

Now both apps migrations are aware of the change and life sucks just a little less :-) Setting this relationship between migrations is key of success. Now if you do:

python manage.py migrate common
 > specific: 0003_create_cat
 > common: 0003_drop_cat

将同时进行迁移,并且

python manage.py migrate specific 0002_create_dog
 < common: 0003_drop_cat
 < specific: 0003_create_cat

会向下迁移.

请注意,对于架构的升级,我使用了通用应用程序,而对于降级,我使用了特定的应用程序.那是因为这里的依赖是如何工作的.