Enable integrity checking with sqlite in django

会有一股神秘感。 提交于 2019-12-18 04:08:58

问题


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

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.

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

Any ideas?


回答1:


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)



回答2:


You could use django signals, listening to post_syncdb.

from django.db.models.signals import post_syncdb

def set_pragma_on(sender, **kwargs):
    "your code here"

post_syncdb.connect(set_pragma_on)

This ensures that whenever syncdb is run (syncdb is run, when creating the test database), that your SQLite database has set 'pragma' to 'on'. You should check which database you are using in the above method 'set_pragma_on'.



来源:https://stackoverflow.com/questions/6745763/enable-integrity-checking-with-sqlite-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!