9

I have a Django web-server configured to use SQLite.

In a many-to-many relationship (with extra fields), Django forces me to use the relationship model to establish a relationship between two objects. But I'm able to create a relationship between objects, that don't yet exist in the related tables.

For e.g:

I have table1 and table2 which are related via table12.
In table1, there is just one object called A.
In table2, there is just one object called X.
I can create a record in table12 that depict a relationship between A & Y; even though Y doesn't exist in table2.

My relationship model has marked the foreign keys appropriately.

mynk
  • 1,194
  • 2
  • 13
  • 16

1 Answers1

16

SQLite does not enforce foreign key constraints by default (mostly to be backward compatible).

To enable it, you have to execute

PRAGMA foreign_keys = 1

after you connected to the database.

See the manual about PRAGMA foreign_keys for more details.

Johannes Kuhn
  • 14,778
  • 4
  • 49
  • 73
  • 1
    Also found a way to enable it in Django! http://stackoverflow.com/questions/6745763/enable-integrity-checking-with-sqlite-in-django – mynk Jun 20 '13 at 12:42
  • 6
    A slightly nicer variant would be `PRAGMA foreign_keys=ON` rather than `1` – Ron Kalian Dec 21 '18 at 14:04