Place to set SQLite PRAGMA option in Django project
Asked Answered
A

2

13

According to this test, setting PRAGMA synchronous=OFF 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.

Arrive answered 26/12, 2010 at 18:53 Comment(0)
S
23

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)
Sip answered 27/7, 2011 at 10:57 Comment(1)
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.Adinaadine
H
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.

Howe answered 7/3, 2011 at 13:17 Comment(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.Evante

© 2022 - 2024 — McMap. All rights reserved.