在django中使用sqlite启用完整性检查 [英] Enable integrity checking with sqlite in django

查看:184
本文介绍了在django中使用sqlite启用完整性检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my django project, I use mysql db for production, and sqlite for tests.

问题是,我的一些代码依赖于模型完整性检查。它与mysql很好地工作,但是在测试中执行相同的代码时,不会抛出完整性错误。

Problem is, some of my code rely on model integrity checking. It works well with mysql, but integrity errors are not thrown when the same code is executed in tests.

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

I know that foreign keys checking must be activated in sqlite :

PRAGMA foreign_keys = 1;

但是,我不知道执行此激活的最佳方式在哪里(这里的问题)。

However, I don't know where is the best way to do this activation (same question here).

此外,以下代码将无法正常工作:

Moreover, the following code won't work :

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,)

任何想法?

推荐答案

所以,如果终于找到正确的答案。我只需要在我安装的应用程序之一的 __ init __。py 文件中添加此代码:

So, if finally found the correct answer. All I had to do was to add this code in the __init__.py file in one of my 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)

这篇关于在django中使用sqlite启用完整性检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆