12

According to this test, setting PRAGMA synchronous=OFF Sqlite can dramatically improve Sqlite write performance.

I am well aware of the drawbacks, but would still like to try this out.

What would be the best location within a Django project to set this PRAGMA option?

I cannot do it from settings.py - at least not the way the article suggests - because from django.db import connection would cause a recursive import error.

Tomas Andrle
  • 13,132
  • 15
  • 75
  • 92

2 Answers2

19

Add this code in the __init__.py file of one of your installed app:

from django.db.backends.signals import connection_created
def activate_foreign_keys(sender, connection, **kwargs):
    """Enable integrity constraint with sqlite."""
    if connection.vendor == 'sqlite':
        cursor = connection.cursor()
        cursor.execute('PRAGMA foreign_keys = ON;')

connection_created.connect(activate_foreign_keys)
Pi Delport
  • 10,356
  • 3
  • 36
  • 50
Thibault J
  • 4,336
  • 33
  • 44
  • Nice and clean solution, will try. Thanks! – Tomas Andrle Jul 27 '11 at 18:15
  • Although I removed my DB file, removed all the previous migrations, and created new migrations, this made no difference for me. The tables were not created with "on delete cascade" as expected. I wonder why that's not happening. – Mr. Lance E Sloan Mar 11 '16 at 17:52
0

The article suggests that you add that as a middleware (at the very end). That middleware is then configured as a string inside settings.py, so you shouldn't get any import conflicts.

Emil Stenström
  • 13,329
  • 8
  • 53
  • 75
  • 1
    This is quite an old thread, but may I still point out that middlewares are called at each request, and therefore may not be the ideal place for sqlite pragmas like setting `synchronous`, since it feels more like a one-off decision. – Arnaud P Feb 25 '19 at 16:01