Enable integrity checking with sqlite in django

前端 未结 2 1065
天命终不由人
天命终不由人 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:10

    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'.

    0 讨论(0)
  • 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)
    
    0 讨论(0)
提交回复
热议问题