Enable integrity checking with sqlite in django

前端 未结 2 1071
天命终不由人
天命终不由人 2020-12-16 20:27

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

2条回答
  •  不知归路
    2020-12-16 21:26

    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)
    

提交回复
热议问题