TransactionManagementError “Transaction managed block ended with pending COMMIT/ROLLBACK" while making migrations in Django

347 views Asked by At

When I make the migrations using python manage.py migrate manage (yes it's Django 1.8 and I can't change it :/), the migrations (every single one I tested) always fail with the same error :

django.db.transaction.TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK

enter image description here

Here is the code from the migration file :

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Check expiry keys in Organization
        for org in Organization.objects.all():
            self.checkExpiryDate(org)
        # Check expiry keys in UserProfileRoleInOrganization
        for uprio in UserProfileRoleInOrganization.objects.all():
            self.checkExpiryDate(uprio)

    def checkExpiryDate(self, entity):
        # Check if expiry_date is consistent with apikey and fix it if necessary
        if not entity.date_has_changed:
            return
        date_in_key = entity.getExpiryDateInKey()
        if not date_in_key:
            return
        y = int(date_in_key[:4])
        m = int(date_in_key[4:-2])
        d = int(date_in_key[-2:])
        entity.expiry_date = datetime.datetime(y,m,d)
        entity.save()

    def backwards(self, orm):
        pass

I've seen some answers to other similar questions but no, I don't have any @commit.... decorator in my code.

May somebody help me please ?

2

There are 2 answers

1
Suhas Kashyap On BEST ANSWER

Delete the migrations folder and re run migrations ./manage.py makemigrations app ./manage.py migrate

or

You also can fake the migrations and reset it

2
Mario Orlandi On

In a data migration, you should avoid importing the Model directly, since the "actual" Model might be inconsistent with previous migrations.

So, for example, use:

# We can't import the Person model directly as it may be a newer
# version than this migration expects. We use the historical version.
Person = apps.get_model('yourappname', 'Person')

instead of

from yourappname.models import Person

See: https://docs.djangoproject.com/en/3.0/topics/migrations/#data-migrations

This at least with recent versions of Django; I don't remember exactly how to cope with this with South

You might also try to add this option to the DATABASES['default'] definition:

'OPTIONS': {'autocommit': True,}

since with Django 1.8 the default for autocommit was False (probably); sometimes, this helps in receiving the proper db exception.