如果在某些地方已经有null值,我怎么能将null = True字段更改为null = False字段?

时间:2017-08-23 14:58:47

标签: python django django-migrations

django.db.utils.OperationalError: cannot ALTER TABLE "news_article" because it has pending trigger events

所以,我有以下问题:

我有一个Django类,文章,其中包含几个Char-和TextFields。它们被设置为blank=Truenull=True,这是......不幸的。哦,不,我需要解决这个问题。因此,在删除null=True并设置default=''后,我在迁移中写了以下内容:

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

from django.db import models, migrations
import languagefields.utils
from languagefields.utils import LANGUAGES
from django.utils.translation import activate
from news.models import Article


def null_migrations(apps, schema_editor):
    activate('en')
    fields = ['short_title', 'description']
    for p in Article.objects.all():
        for l in LANGUAGES:
            for f in fields:
                if p.get_language(l, f) is None:
                    p.set_localized(l, f, '')
                    p.save()


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(null_migrations),
        migrations.AlterField(....

这些字段是自定义字段,基于默认的Char- / TextFields,可以进行翻译。所以有很多。对于您创建的每个字段,将有5个,英语,德语等的描述...所以是的,小功能正常工作,我在服务器上运行它并手动清理数据库条目,但这不会停止上面的例外。所以我以为我会把它放在迁移中以便随时清理。但仍然是例外。我做错了什么?

提前谢谢你:)

修改

将迁移分成两部分:

0002_null_cleaning.py

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

from django.db import models, migrations
import languagefields.utils
from languagefields.utils import LANGUAGES
from django.utils.translation import activate
from news.models import Article


def null_migrations(apps, schema_editor):
    activate('en')
    fields = ['short_title', 'description']
    for p in Article.objects.all():
        for l in LANGUAGES:
            for f in fields:
                if p.get_language(l, f) is None:
                    p.set_localized(l, f, '')
                    p.save()


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0001_initial'),
    ]

    operations = [
        migrations.RunPython(null_migrations),
]

0003_data_migration

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

from django.db import models, migrations
import languagefields.utils


class Migration(migrations.Migration):

    dependencies = [
        ('news', '0002_null_cleaning'),
    ]

    operations = [
        migrations.AlterField(...

0003

发生了同样的错误

1 个答案:

答案 0 :(得分:0)

我认为您必须将迁移分为2个实际迁移。它们应该在事务中发生,因此更改数据和更改表可能不是犹太教。只需创建两个迁移,它应该工作。