django手写迁移改变了认证

时间:2015-07-13 14:02:19

标签: django database-migration django-migrations

我正在使用django 1.8.1并尝试从我的某个应用程序中扩展auth_user名称字段的长度。之前,在南方,我可以用下划线来定位应用程序,如下所示:

db.alter_column('auth_group', 'name', models.CharField(max_length=120, null=False, blank=False))

然而,在django 1.8中,我没有看到这样做的方法,因为django使用源代码在sql中推送应用程序名称。我不想编辑django源代码,所以我无法改变它。我目前的尝试是在这里:

class Migration(migrations.Migration):

dependencies = [
    ('auth', '0006_require_contenttypes_0002'),
]       

operations = [
    migrations.AlterField('auth_group', 'name', field=models.CharField(max_length=120, null=False, blank=False)),
]

请帮忙。我不想编辑django源代码,我只想做migrations.RunSQL作为最后的手段。

2 个答案:

答案 0 :(得分:0)

嗯,有一个棘手的方法:

# -*- coding: utf-8 -*-
from django.db.migrations import Migration as DjangoMigration, AlterField
from django.db.models import CharField


class Migration(DjangoMigration):
    dependencies = [
        # Specify other dependencies, if required.
        ('auth', '0006_require_contenttypes_0002')
    ]
    operations = [
        AlterField(
            model_name='User',
            name='username',
            field=CharField(max_length=120)
        )
    ]

    def mutate_state(self, project_state, preserve=True):
        """
        This is a workaround that allows to store ``auth``
        migration outside the directory it should be stored.
        """
        app_label = self.app_label
        self.app_label = 'auth'
        state = super(Migration, self).mutate_state(project_state, preserve)
        self.app_label = app_label
        return state

    def apply(self, project_state, schema_editor, collect_sql=False):
        """
        Same workaround as described in ``mutate_state`` method.
        """
        app_label = self.app_label
        self.app_label = 'auth'
        state = super(Migration, self).apply(project_state, schema_editor, collect_sql)
        self.app_label = app_label
        return state

将此信息放入应用程序的migrations文件夹中,并使用正确的名称,例如0001_alter_auth_user_username.py

但是,我不确定这是一个好方法。

答案 1 :(得分:0)

谢谢@Ernest Ten。

就我而言,我依赖于:

    dependencies = [ # Specify other dependencies, if required. ('auth', '0004_alter_user_username_opts') ]

确保运行“python manage.py migrate”以将此反映给您db。