Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
202 views
in Technique[技术] by (71.8m points)

django handwritten migrations altering auth

I am using django 1.8.1 and trying to extend the length of auth_user name field from one of my apps. Before, with south, I could just target the app with an underscore like so:

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

However, in django 1.8, I don't see a way to do this as django putts the app name in the sql withing the source code. I don't want to edit django source code so I have no way of changing that. my current attemp is here:

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)),
]

Please help. I don't want to edit django source code and I only want to do migrations.RunSQL as a last resort.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, there is a tricky way to do that:

# -*- 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

Put this in your application's migrations folder with a proper name, e.g. 0001_alter_auth_user_username.py.

I'm not sure, however, that this is a good approach.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...