5

When trying to use SqlLite3 as the DB backend to Django, I'd like to be able to use SqLite's Foreign Key support. According to http://www.sqlite.org/foreignkeys.html, you can enable foreign key support by running:

PRAGMA foreign_keys = ON;

This support is disabled by default, and would be desirable while running most db dependent tests. How would one control this feature while using Django test framework? Can you send backend-specific commands in your setUp/tearDown methods? Would you rather specify this option in connection settings ('DATABASE = ' settings) globally?

Marcin K
  • 871
  • 2
  • 10
  • 17
  • 3
    This answer seems to be what you want: http://stackoverflow.com/questions/6745763/enable-integrity-checking-with-sqlite-in-django/6835016#6835016 – Lycha Nov 07 '11 at 22:32
  • @Lycha that is precisely the answer I was looking for. I should have searched for existing questions better. How do I link that answer to my question? – Marcin K Nov 08 '11 at 15:25

2 Answers2

2

It's partially answered here: https://stackoverflow.com/a/6843142/552671.

You can just activate it in your app (typically in myapp/apps.py).

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;')

class MyAppConfig(AppConfig):
    def ready(self):
        connection_created.connect(activate_foreign_keys)

You have to configure MyAppConfig as well, write default_app_config = 'myapp.apps.PanelConfig' to myapp/__init__.py.

Note: This will activate foreign keys not only for tests but also SQLite in general. I think that is what you want, though.

Community
  • 1
  • 1
Dave Halter
  • 15,556
  • 13
  • 76
  • 103
2

In current django it is not needed anymore. Closed in https://code.djangoproject.com/ticket/14204

And from 2.2 it is also on during unit testing :)

Michel Samia
  • 4,273
  • 2
  • 24
  • 24