关于django:迁移时传递South随机唯一默认值

Pass South random unique default values when migrating

我正在尝试使用现有数据向前迁移模型。该模型有一个新字段,其中约束unique=true,null=false。当我这样做的时候

1
./manage.py schemamigration myapp --auto

South允许我通过请求为新字段指定默认值:

1
Specify a one-off value to use for existing columns now

通常我将其设置为"无",但由于此字段需要唯一,我想知道是否可以通过以下方式将唯一值传递给南方:

1
 >>> import uuid; uuid.uuid1().hex[0:35]

这会给我一个错误信息

1
! Invalid input: invalid syntax

如果可以在通过命令行迁移时传递南方随机唯一默认值,有什么想法吗?

谢谢。


不幸的是,在模式迁移中,只有datetime模块可用作一次性值。

但是,您可以通过将其分为三个迁移来实现相同的效果:

  • 向模型中添加不带约束的新字段(空=真,唯一=假)
  • 使用数据迁移将UUID添加到新字段
  • 在新字段上添加约束(空=假,唯一=真)

数据迁移教程:http://south.readthedocs.org/en/0.7.6/tutorial/part3.html数据迁移


在Django 1.7+中,您可以执行以下操作。它首先添加没有索引和唯一性的字段。然后它分配唯一的值(我基于名称并使用您需要创建的sligify方法),最后再次修改字段以添加索引和唯一属性。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from django.db import migrations
import re
import django.contrib.postgres.fields
from common.utils import slugify
import django.core.validators


def set_slugs(apps, schema_editor):
    categories = apps.get_model("myapp","Category").objects.all()
    for category in categories:
        category.slug = slugify(category.name)
        category.save()


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0034_auto_20150906_1936'),
    ]

    operations = [
        migrations.AddField(
            model_name='category',
            name='slug',
            field=models.CharField(max_length=30, validators=[django.core.validators.MinLengthValidator(2), django.core.validators.RegexValidator(re.compile('^[0-9a-z-]+$'), 'Enter a valid slug.', 'invalid')], help_text='Required. 2 to 30 characters and can only contain a-z, 0-9, and the dash (-)', unique=False, db_index=False, null=True),
            preserve_default=False,
        ),
        migrations.RunPython(set_slugs),
        migrations.AlterField(
            model_name='category',
            name='slug',
            field=models.CharField(help_text='Required. 2 to 30 characters and can only contain a-z, 0-9, and the dash (-)', unique=True, max_length=30, db_index=True, validators=[django.core.validators.MinLengthValidator(2), django.core.validators.RegexValidator(re.compile('^[0-9a-z-]+$'), 'Enter a valid slug.', 'invalid')]),
        ),
    ]


这是Django关于迁移独特字段的官方操作方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
Migrations that add unique fields
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

 Applying a"plain" migration that adds a unique non-nullable field to a table
 with existing rows will raise an error because the value used to populate
 existing rows is generated only once, thus breaking the unique constraint.

 Therefore, the following steps should be taken. In this example, we'll add a
 non-nullable :class:`~django.db.models.UUIDField` with a default value. Modify
 the respective field according to your needs.

 * Add the field on your model with ``default=...`` and ``unique=True``
   arguments. In the example, we use ``uuid.uuid4`` for the default.

 * Run the :djadmin:`makemigrations` command.

 * Edit the created migration file.

   The generated migration class should look similar to this::

     class Migration(migrations.Migration):

         dependencies = [
             ('myapp', '0003_auto_20150129_1705'),
         ]

         operations = [
             migrations.AddField(
                 model_name='mymodel',
                 name='uuid',
                 field=models.UUIDField(max_length=32, unique=True, default=uuid.uuid4),
             ),
         ]

   You will need to make three changes:

   * Add a second :class:`~django.db.migrations.operations.AddField` operation
     copied from the generated one and change it to
     :class:`~django.db.migrations.operations.AlterField`.

   * On the first operation (``AddField``), change ``unique=True`` to
     ``null=True`` -- this will create the intermediary null field.

   * Between the two operations, add a
     :class:`~django.db.migrations.operations.RunPython` or
     :class:`~django.db.migrations.operations.RunSQL` operation to generate a
     unique value (UUID in the example) for each existing row.

   The resulting migration should look similar to this::

     # -*- coding: utf-8 -*-
     from __future__ import unicode_literals

     from django.db import migrations, models
     import uuid

     def gen_uuid(apps, schema_editor):
         MyModel = apps.get_model('myapp', 'MyModel')
         for row in MyModel.objects.all():
             row.uuid = uuid.uuid4()
             row.save()

     class Migration(migrations.Migration):

         dependencies = [
             ('myapp', '0003_auto_20150129_1705'),
         ]

         operations = [
             migrations.AddField(
                 model_name='mymodel',
                 name='uuid',
                 field=models.UUIDField(default=uuid.uuid4, null=True),
             ),
             # omit reverse_code=... if you don't want the migration to be reversible.
             migrations.RunPython(gen_uuid, reverse_code=migrations.RunPython.noop),
             migrations.AlterField(
                 model_name='mymodel',
                 name='uuid',
                 field=models.UUIDField(default=uuid.uuid4, unique=True),
             ),
         ]
* Now you can apply the migration as usual with the :djadmin:`migrate` command.

   Note there is a race condition if you allow objects to be created while this
   migration is running. Objects created after the ``AddField`` and before
   ``RunPython`` will have their original ``uuid``’s overwritten.


有一种方法可以为每一行的南方值。

在models.py中将slug定义为:

1
2
3
class Foo(models.Model):
  slug = models.SlugField(unique=True, default='')
  ....

创建新迁移

运行python manage.py模式迁移--自动foo

打开新的迁移文件,并对其进行编辑:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Change add_column to this:
db.add_column(u'account_funnel', 'slug',
            self.gf('django.db.models.foo.Foo')(default='',
                  unique=False,  
                  max_length=50),
            keep_default=False)

# right above this add such python code:
foos = orm['foo.Foo'].objects.all()
for foo in foos:
        foo.slug = slugify(funnel.name)
        foo.save()

# Modify slug as unique field
db.create_unique(u'foo_foo', ['slug'])

ps mark this migration as no_dry_run = True
pss do not forget to import slugify function from django.template.defaultfilters import slugify

您可以手动编辑迁移文件:

我需要在某个字段中添加随机字符,所以我导入了Random和Randint

1
2
import random
import string

并将默认值更改为

1
default=random.choice(string.lowercase)

它奏效了。