131

我有一个 django 应用程序,里面有四个模型。我现在意识到这些模型之一应该在一个单独的应用程序中。我确实为迁移安装了南,但我认为这不是它可以自动处理的。如何将其中一个模型从旧应用程序迁移到新应用程序中?

另外,请记住,我将需要这是一个可重复的过程,以便我可以迁移生产系统等。

4

7 回答 7

188

如何使用南方迁移。

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

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)。首先在源代码中进行更改,然后运行:

$ 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

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

#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

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

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

会将事情向下迁移。

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

于 2009-11-20T12:22:04.220 回答
35

Potr Czachur回答为基础,涉及 ForeignKeys 的情况更复杂,处理方式应略有不同。

(以下示例建立在当前答案中引用的common和应用程序的基础上)。specific

# common/models.py

class Cat(models.Model):
    # ...

class Toy(models.Model):
    belongs_to = models.ForeignKey(Cat)
    # ...

然后将更改为

# common/models.py

from specific.models import Cat

class Toy(models.Model):
    belongs_to = models.ForeignKey(Cat)
    # ...

# specific/models.py

class Cat(models.Model):
    # ...

跑步

./manage.py schemamigration common --auto
./manage.py schemamigration specific --auto # or --initial

将生成以下迁移(我故意忽略 Django ContentType 更改 - 请参阅先前引用的答案以了解如何处理):

# common/migrations/0009_auto__del_cat.py

class Migration(SchemaMigration):
    def forwards(self, orm):
        db.delete_table('common_cat')
        db.alter_column('common_toy', 'belongs_to_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['specific.Cat']))

    def backwards(self, orm):
        db.create_table('common_cat', (
            # ...
        ))
        db.alter_column('common_toy', 'belongs_to_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['common.Cat']))

# specific/migrations/0004_auto__add_cat.py

class Migration(SchemaMigration):
    def forwards(self, orm):
        db.create_table('specific_cat', (
            # ...
        ))

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

如您所见,必须更改 FK 以引用新表。我们需要添加一个依赖项,以便我们知道应用迁移的顺序(因此在我们尝试向其添加 FK 之前该表将存在),但我们还需要确保向后滚动也有效,因为相关性适用于相反的方向

# common/migrations/0009_auto__del_cat.py

class Migration(SchemaMigration):

    depends_on = (
        ('specific', '0004_auto__add_cat'),
    )

    def forwards(self, orm):
        db.alter_column('common_toy', 'belongs_to_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['specific.Cat']))

    def backwards(self, orm):
        db.rename_table('specific_cat', 'common_cat')
        db.alter_column('common_toy', 'belongs_to_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['common.Cat']))

# specific/migrations/0004_auto__add_cat.py

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

    def backwards(self, orm):
        pass

根据South 文档depends_on将确保在向前迁移时0004_auto__add_cat运行在之前, 但在向后迁移时以相反的顺序运行。如果我们留在回滚中,则在尝试迁移 ForeignKey 时回滚将失败,因为表引用的表将不存在。0009_auto__del_cat db.rename_table('specific_cat', 'common_cat')specificcommon

希望这比现有解决方案更接近“真实世界”的情况,并且有人会发现这很有帮助。干杯!

于 2012-08-22T20:20:57.147 回答
13

模型与应用程序的耦合不是很紧密,因此移动相当简单。Django 在数据库表的名称中使用应用程序名称,因此如果您想移动应用程序,您可以通过 SQLALTER TABLE语句重命名数据库表,或者 - 更简单 - 只需使用模型类中的db_table参数Meta来引用旧名。

如果到目前为止您在代码中的任何地方都使用过 ContentTypes 或泛型关系,您可能希望重命名app_label指向正在移动的模型的内容类型,以便保留现有关系。

当然,如果您根本没有任何数据要保留,最简单的做法是完全删除数据库表并./manage.py syncdb再次运行。

于 2009-08-11T06:40:17.380 回答
4

这是对 Potr 出色解决方案的又一修复。将以下内容添加到特定/0003_create_cat

depends_on = (
    ('common', '0002_create_cat'),
)

除非设置此依赖项,否则 South 将不保证在运行specific/0003_create_catcommon_cat时该表存在,从而向您抛出错误。django.db.utils.OperationalError: no such table: common_cat

除非明确设置依赖关系,否则South 按字典顺序运行迁移。由于在表重命名common之前specific所有common的迁移都会运行,所以它可能不会在 Potr 显示的原始示例中重现。但是如果你重命名commonapp2和你specificapp1遇到这个问题。

于 2014-01-23T15:36:38.680 回答
4

自从我回到这里几次并决定将其正式化以来,我目前已经确定了这个过程。

这最初是建立在 Potr Czachur's answerMatt Briançon's answer 的基础上,使用 South 0.8.4

步骤 1. 发现子外键关系

# Caution: This finds OneToOneField and ForeignKey.
# I don't know if this finds all the ways of specifying ManyToManyField.
# Hopefully Django or South throw errors if you have a situation like that.
>>> Cat._meta.get_all_related_objects()
[<RelatedObject: common:toy related to cat>,
 <RelatedObject: identity:microchip related to cat>]

因此,在这个扩展案例中,我们发现了另一个相关模型,例如:

# Inside the "identity" app...
class Microchip(models.Model):

    # In reality we'd probably want a ForeignKey, but to show the OneToOneField
    identifies = models.OneToOneField(Cat)

    ...

步骤 2. 创建迁移

# Create the "new"-ly renamed model
# Yes I'm changing the model name in my refactoring too.
python manage.py schemamigration specific create_kittycat --auto

# Drop the old model
python manage.py schemamigration common drop_cat --auto

# Update downstream apps, so South thinks their ForeignKey(s) are correct.
# Can skip models like Toy if the app is already covered
python manage.py schemamigration identity update_microchip_fk --auto

步骤 3. 源代码控制:提交到目前为止的更改。

如果您遇到合并冲突,例如队友在更新的应用程序上编写迁移,则使其成为一个更可重复的过程。

步骤 4. 添加迁移之间的依赖关系。

基本上create_kittycat取决于一切的当前状态,然后一切都取决于create_kittycat.

# create_kittycat
class Migration(SchemaMigration):

    depends_on = (
        # Original model location
        ('common', 'the_one_before_drop_cat'),

        # Foreign keys to models not in original location
        ('identity', 'the_one_before_update_microchip_fk'),
    )
    ...


# drop_cat
class Migration(SchemaMigration):

    depends_on = (
        ('specific', 'create_kittycat'),
    )
    ...


# update_microchip_fk
class Migration(SchemaMigration):

    depends_on = (
        ('specific', 'create_kittycat'),
    )
    ...

第 5 步。我们要进行的表重命名更改。

# create_kittycat
class Migration(SchemaMigration):

    ...

    # Hopefully for create_kittycat you only need to change the following
    # 4 strings to go forward cleanly... backwards will need a bit more work.
    old_app = 'common'
    old_model = 'cat'
    new_app = 'specific'
    new_model = 'kittycat'

    # You may also wish to update the ContentType.name,
    # personally, I don't know what its for and
    # haven't seen any side effects from skipping it.

    def forwards(self, orm):

        db.rename_table(
            '%s_%s' % (self.old_app, self.old_model),
            '%s_%s' % (self.new_app, self.new_model),
        )

        if not db.dry_run:
            # For permissions, GenericForeignKeys, etc to work properly after migrating.
            orm['contenttypes.contenttype'].objects.filter(
                app_label=self.old_app,
                model=self.old_model,
            ).update(
                app_label=self.new_app,
                model=self.new_model,
            )

        # Going forwards, should be no problem just updating child foreign keys
        # with the --auto in the other new South migrations

    def backwards(self, orm):

        db.rename_table(
            '%s_%s' % (self.new_app, self.new_model),
            '%s_%s' % (self.old_app, self.old_model),
        )

        if not db.dry_run:
            # For permissions, GenericForeignKeys, etc to work properly after migrating.
            orm['contenttypes.contenttype'].objects.filter(
                app_label=self.new_app,
                model=self.new_model,
            ).update(
                app_label=self.old_app,
                model=self.old_model,
            )

        # Going backwards, you probably should copy the ForeignKey
        # db.alter_column() changes from the other new migrations in here
        # so they run in the correct order.
        #
        # Test it! See Step 6 for more details if you need to go backwards.
        db.alter_column('common_toy', 'belongs_to_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['common.Cat']))
        db.alter_column('identity_microchip', 'identifies_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['common.Cat']))


# drop_cat
class Migration(SchemaMigration):

    ...

    def forwards(self, orm):
        # Remove the db.delete_table(), if you don't at Step 7 you'll likely get
        # "django.db.utils.ProgrammingError: table "common_cat" does not exist"

        # Leave existing db.alter_column() statements here
        db.alter_column('common_toy', 'belongs_to_id', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['specific.KittyCat']))

    def backwards(self, orm):
        # Copy/paste the auto-generated db.alter_column()
        # into the create_kittycat migration if you need backwards to work.
        pass


# update_microchip_fk
class Migration(SchemaMigration):

    ...

    def forwards(self, orm):
        # Leave existing db.alter_column() statements here
        db.alter_column('identity_microchip', 'identifies_id', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['specific.KittyCat']))

    def backwards(self, orm):
        # Copy/paste the auto-generated db.alter_column()
        # into the create_kittycat migration if you need backwards to work.
        pass

第 6 步。仅当您需要向后()工作并获得 KeyError 向后运行时。

# the_one_before_create_kittycat
class Migration(SchemaMigration):

    # You many also need to add more models to South's FakeORM if you run into
    # more KeyErrors, the trade-off chosen was to make going forward as easy as
    # possible, as that's what you'll probably want to do once in QA and once in
    # production, rather than running the following many times:
    #
    # python manage.py migrate specific <the_one_before_create_kittycat>

    models = {
        ...
        # Copied from 'identity' app, 'update_microchip_fk' migration
        u'identity.microchip': {
            'Meta': {'object_name': 'Microchip'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'identifies': ('django.db.models.fields.related.OneToOneField', [], {to=orm['specific.KittyCat']})
        },
        ...
    }

第 7 步。测试它 - 对我有用的方法可能不足以满足您的实际生活情况 :)

python manage.py migrate

# If you need backwards to work
python manage.py migrate specific <the_one_before_create_kittycat>
于 2014-08-01T06:32:02.083 回答
3

因此,在 South 0.8.1 和 Django 1.5.1 上,使用上面 @Potr 的原始响应对我不起作用。我在下面发布了对我有用的内容,希望对其他人有所帮助。

from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

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

        if not db.dry_run:
             db.execute(
                "update django_content_type set app_label = 'specific' where "
                " app_label = 'common' and model = 'cat';")

    def backwards(self, orm):
        db.rename_table('specific_cat', 'common_cat')
            db.execute(
                "update django_content_type set app_label = 'common' where "
                " app_label = 'specific' and model = 'cat';")
于 2013-12-13T10:07:16.203 回答
1

我将给出丹尼尔罗斯曼在他的回答中建议的事情之一的更明确的版本......

如果您只是更改db_table已移动模型的 Meta 属性以指向现有表名(而不是如果您删除并执行了 Django 将给它的新名称syncdb),那么您可以避免复杂的南迁移。例如:

原来的:

# app1/models.py
class MyModel(models.Model):
    ...

搬家后:

# app2/models.py
class MyModel(models.Model):
    class Meta:
        db_table = "app1_mymodel"

现在您只需要进行数据迁移以更新表中 的app_labelfor就可以了……MyModeldjango_content_type

运行./manage.py datamigration django update_content_type然后编辑 South 为您创建的文件:

def forwards(self, orm):
    moved = orm.ContentType.objects.get(app_label='app1', model='mymodel')
    moved.app_label = 'app2'
    moved.save()

def backwards(self, orm):
    moved = orm.ContentType.objects.get(app_label='app2', model='mymodel')
    moved.app_label = 'app1'
    moved.save()
于 2014-01-23T08:00:57.937 回答