2015-07-13 28 views
0

我正在使用django 1.8.1,并试图从我的一个应用程序扩展auth_user名称字段的长度。之前,与韩国,我可以只针对应用程序,象这样一个下划线:django手写迁移改变验证

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

然而,在Django 1.8,我没有看到一个办法做到这一点是Django的在SQL withing的推杆应用程序名称源代码。我不想编辑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作为最后的手段。

回答

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 

有一个合适的名字,例如把这个应用程序的文件夹migrations0001_alter_auth_user_username.py

但我不确定这是否是一种好方法。

+0

因此,本质上,我正在改变整个迁移类的应用程序名称? –

+0

@IanKirkpatrick您正在某些地方更改它,以便迁移可以从正确的应用程序获取模型,即''用户'模型将从'auth'应用程序获得,同时迁移本身将属于您的项目。 –

0

谢谢@Ernest十。

就我而言,我一直在依赖:

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

确保您运行“蟒蛇manage.py迁移”得到这个反映到你分贝。