Django 1.6 TransactionManagementError: database doesn't behave properly when autocommit is off
I ran into this with sqlite3 db, using Django 1.6. Here are the solutions.
django.middleware.transaction.TransactionMiddleware has been deprecated. If you don't have this in your settings.py file, you should not get the error.
Accidentally, I found that including ATOMIC_REQUESTS: True works around the error if you had left django.middleware.transaction.TransactionMiddleware in your middlewares list.
E.g.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'sqlite3-db', 'ATOMIC_REQUESTS': True }}
I had the same issue in my forwards
migration (interestingly, didn't happen in my backwards
migration), and don't have TransactionMiddleware
in my settings. My workaround was to avoid using the get_or_create
method and instead do the same thing more verbosely. From the Django docs:
try: obj = Person.objects.get(first_name='John', last_name='Lennon')except Person.DoesNotExist: obj = Person(first_name='John', last_name='Lennon', birthday=date(1940, 10, 9)) obj.save()
You can then create your own pseudo-get_or_create
method like this:
def fake_get_or_create(model, *args, **kwargs): try: obj = model.objects.get(**kwargs) except model.DoesNotExist: obj = model(**kwargs) obj.save() return obj
Which you can use by doing the following
obj = fake_get_or_create(Person, first_name='John', last_name='Lennon')
I ran into the same problem when using sqlite3. I found out that I was using transaction.commit_on_success
. On changing that to transaction.atomic()
, the problem was resolved.