我正在尝试使用 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 固定装置的功能。
我的迁移文件:
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)