cannot alter table because it has pending trigger events
Aug. 9, 2016, 6:18 a.m.
You can see error cannot alter table because it has pending trigger events when property of your fields in database is cannot change in one transaction. To understand easy you can see examples.
Romeve blank=True in fields
So, there is model:
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible class MyModel(models.Model): title = models.CharField(max_length=100, null=True, blank=True) content = models.TextField(null=True, blank=True) template = models.CharField(max_length=255, null=True, blank=True) def __str__(self): return self.title
So null=True is extra useless property for CharField, TextField then you need remove null=True:
... class MyModel(models.Model): title = models.CharField(max_length=100, blank=True) content = models.TextField(blank=True) template = models.CharField(max_length=255, blank=True) ...
Then run makemigrations. Note, if to run migrate now, then it gets error cannot alter table because it has pending trigger events. To fix this, write set_blank(apps, schema_editor) in created migration and added migrations.RunPython(set_blank) in operations list for running of our method:
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def set_blank(apps, schema_editor): fields = ('content', 'template', 'title') for obj in apps.get_model('my_app', 'MyModel').objects.all(): old_field_values = {field: getattr(obj, field) for field in fields} for field in fields: setattr(obj, field, getattr(obj, field) or '') dirty = False for field, value in old_field_values.items(): if value != getattr(obj, field): dirty = True if dirty: obj.save() def set_blank_simple(apps, schema_editor): MyModel = apps.get_model('my_app', 'MyModel') for obj in MyModel.objects.all(): obj.content = obj.content or '' obj.template = obj.template or '' obj.title = obj.title or '' obj.save() class Migration(migrations.Migration): dependencies = [ ('my_app', '0007_auto_20160509_1225'), ] operations = [ # migrations.RunPython(set_blank_simple), # simple function migrations.RunPython(set_blank), # more optimized function migrations.AlterField( model_name='mymodel', name='content', field=models.TextField(default='', blank=True), preserve_default=False, ), migrations.AlterField( model_name='mymodel', name='template', field=models.CharField(default='', max_length=255, blank=True), preserve_default=False, ), migrations.AlterField( model_name='mymodel', name='title', field=models.CharField(default='', max_length=100, blank=True), preserve_default=False, ), ]
And error must be fixed. If error was not fixed then you need see to all changed fields more careful. May be, they are not ready to change in one transaction.
Comments: 0