Understanding / mySQL aka tricking ForeignKey relationships in Django

前端 未结 2 1553
耶瑟儿~
耶瑟儿~ 2021-01-06 10:00

So I\'ve inherited some django.

The mySQL table is simple enough where parent is NOT a FK relationship just the \"Parent\" id:

CREATE TABLE `Child` (         


        
相关标签:
2条回答
  • 2021-01-06 10:18

    Its supposed to be faster ... since you mysql doesn't check the constraint before adding a row in the child table. But with the foreign key, it would make your life easier since you can use the on update and on delete. I'd go with the constraint.

    0 讨论(0)
  • 2021-01-06 10:27
    1. Not having an actual constraint might lead to broken references, invalid parents and other sorts of data inconsistencies. I am not a Django expert but I would venture a guess that in most cases Django will still handle the relations fine unless you purposefully add some invalid records.

    2. Normally, if your RDBMS supports foreign key constraints, there is absolutely no reason not to use them, and it could potentially be considered a design flaw to ignore them.

    3. You should consider adding the key constraints. Not only do they give your DBMS a good idea of how to optimize the queries, they also ensure consistency in your data. I am pretty sure Django has a setting somewhere that will automatically generate the SQL to add the key constraints when you run manage.py syncdb

    For more information about why you should prefer foreign keys, you should read the MySQL Foreign Key Documentation

    Most interestingly:

    InnoDB requires indexes on foreign keys and referenced keys so that foreign key checks can be fast and not require a table scan. In the referencing table, there must be an index where the foreign key columns are listed as the first columns in the same order. Such an index is created on the referencing table automatically if it does not exist. (This is in contrast to some older versions, in which indexes had to be created explicitly or the creation of foreign key constraints would fail.) index_name, if given, is used as described previously.

    0 讨论(0)
提交回复
热议问题