本文介绍了了解/ mySQL也是Django中的外键关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我继承了一些django。

So I've inherited some django.

mySQL表很简单,父对象不是FK关系,只是父id:

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

CREATE TABLE `Child` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `parent` int(10) unsigned NOT NULL,
  `name` varchar(255) NOT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=24;

但是创始人做了这个..

But then the originator did this..

class Child(models.Model):
    """Project Child information"""
    id = models.AutoField(primary_key=True)
    parent = models.ForeignKey(Parent)
    name = models.CharField(max_length=255)

    class Meta:
        managed = False

诚然,我不是一个SQL Jockey,但我知道一个真正的外键关系看起来类似于这个通知 CONSTRAINT ...

Admittedly I am NOT a SQL Jockey but I know that a "real" Foreign Key Relationship looks similar to this notice CONSTRAINT...

CREATE TABLE `Child` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `child_63f17a16` (`parent_id`),
  CONSTRAINT `parent_id_refs_id_34923e1e` FOREIGN KEY (`parent_id`) REFERENCES `Parent` (`id`)
) ENGINE=InnoDB;

我想知道的是:


  1. 这个诡计可能会出现什么问题。

  2. 这似乎是有效的 - 推荐或建议。

  3. 我们建议将SQL修改为?

  1. What problems could I expect to see by this "trickery".
  2. While this appears to work - is it recommended or advised.
  3. Would we be advised to modify the SQL to add in the constraint?

非常感谢!

推荐答案


  1. 没有实际的约束可能会导致参考文献错误,父母无效以及其他类型的数据不一致。我不是Django的专家,但是我猜测在大多数情况下,Django仍然会处理关系,除非有意添加一些无效记录。

  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.

如果您的RDBMS支持外键约束,绝对没有理由不使用它们,并且可能被认为是忽略它们的设计缺陷。

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.

您应该考虑添加关键约束。它们不仅可以让您的DBMS了解如何优化查询,还可以确保数据的一致性。我很确定Django有一个设置,当你运行 manage.py syncdb

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

最有趣的是:

这篇关于了解/ mySQL也是Django中的外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:27
查看更多