代码改变世界

django迁移model到别的app中

2019-03-04 17:04  cmsd  阅读(1115)  评论(0编辑  收藏  举报

举例: 移动 users.AccessKey 到 authentication.AccessKey中

 

1. 移动models到新的app中

$ mv users/models/access_key.py authentication/models/

  

2. 原来app中添加migrations

$ python manage.py makemigrations --empty users
$ vim users/migrations/0019_auto_20190304_1459.py
from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('users', '0018_auto_20190107_1912'),
    ]
    # 重命名表
    database_operations = [
        migrations.AlterModelTable(name='accesskey', table='authentication_accesskey'),
    ]
    # 声明已删除了表
    state_operations = [
        migrations.DeleteModel('accesskey'),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(
            database_operations=database_operations,
            state_operations=state_operations)
    ]

 

3. 新的app生成 migrations,编辑生成的migrations文件 

 

$ python manage.py makemigrations authentication
$ vim authentication/migrations/0001_initial.py
# Generated by Django 2.1.7 on 2019-02-28 08:07

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import uuid


class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('users', '0019_auto_20190304_1459'),
    ]

    state_operations = [
        migrations.CreateModel(
            name='AccessKey',
            fields=[
                ('id',
                 models.UUIDField(default=uuid.uuid4, editable=False,
                                  primary_key=True, serialize=False,
                                  verbose_name='AccessKeyID')),
                ('secret',
                 models.UUIDField(default=uuid.uuid4, editable=False,
                                  verbose_name='AccessKeySecret')),
                ('user', models.ForeignKey(
                    on_delete=django.db.models.deletion.CASCADE,
                    related_name='access_keys',
                    to=settings.AUTH_USER_MODEL, verbose_name='User')),
            ],
        ),
    ]

    operations = [
        migrations.SeparateDatabaseAndState(state_operations=state_operations)
    ]

 

4. 完成,可以正常执行migrations等操作了,数据不会丢失

 

更多见:https://stackoverflow.com/questions/25648393/how-to-move-a-model-between-two-django-apps-django-1-7