在django中使用sqlite启用完整性检查

Thi*_*t J 9 sqlite django pragma integrity

在我的django项目中,我使用mysql db进行生产,使用sqlite进行测试.

问题是,我的一些代码依赖于模型完整性检查.它适用于mysql,但在测试中执行相同的代码时不会抛出完整性错误.

我知道必须在sqlite中激活外键检查:

PRAGMA foreign_keys = 1;
Run Code Online (Sandbox Code Playgroud)

但是,我不知道这种激活的最佳方式在哪里(这里也是同样的问题).

此外,以下代码将不起作用:

def test_method(self):
    from django.db import connection
    cursor = connection.cursor()
    cursor.execute('PRAGMA foreign_keys = ON')
    c = cursor.execute('PRAGMA foreign_keys')
    print c.fetchone()
    >>> (0,)
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

Thi*_*t J 17

所以,如果终于找到了正确的答案.我所要做的就是__init__.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;')

connection_created.connect(activate_foreign_keys)
Run Code Online (Sandbox Code Playgroud)