使用数据迁移创建初始数据时的TransactionManagementError

时间:2014-10-19 22:13:35

标签: django django-1.7

我正在尝试使用Django 1.7的新数据迁移来为我的应用创建初始数据。我有标记模型与文本(显示文本)和slug(唯一)字段。当我尝试在数据迁移中执行许多Tag.objects.create()时,我收到此错误:

django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block.

我想知道由于IntegrityError(我故意忽略)事务是否正在中止。我正在尝试替换在使用1.7的新迁移的应用程序中显然已弃用的initial_data fixture的功能。

我的迁移文件:

from django.db import models, migrations, IntegrityError

TAGS = ['Foo', 'Bar', 'Baz', ...]


def populate_initial_tags(apps, schema_editor):

    Tag = apps.get_model('widgets', 'Tag')

    for text in TAGS:
        try:
            Tag.objects.create(text=text)
        except IntegrityError:
            pass


class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.RunPython(populate_initial_tags)
    ]

我的模特

class Tag(models.Model):

    text = models.CharField(max_length=128)
    slug = models.CharField(max_length=128, unique=True)

    def __unicode__(self):
        return self.text

@receiver(pre_save, sender=Tag, dispatch_uid='update_tag_slug')
def update_tag_slug(sender, instance, **kwargs):
    instance.slug = slugify(instance.text)

1 个答案:

答案 0 :(得分:0)

您的猜测是正确的,如果您在交易中(如迁移),则无法忽略IntegrityErrors。而是这样做:

for text in TAGS: 
    try:
        with transaction.atomic():
            Tag.objects.create(text=text)
    except IntegrityError:
        pass

请参阅文档here