我可以避免 django (python) 的 MySQL 表中出现冗余主键列吗?
我知道这样一个事实,如果我使用 Django 的 ORM,每个表都必须有一个主键列。不知何故,如果您有一个链接到表(让我们称其为作者和书籍)的多对多表,您会得到类似的结果:
id author_id book_id
1 1 1
2 1 2
3 2 3
etc.
我遇到过一本书,其中建议避免使用“id”列并创建一个复合主键。这对 django 有用吗?
I am aware of the fact, the if I use the ORM of Django every table has to have a primary key column. Somehow if you have a many_to_many table which links to tables (let's call them authors and books) you would get something like:
id author_id book_id
1 1 1
2 1 2
3 2 3
etc.
I have encountered a book in which it is proposed to avoid the column "id" and to create a compound primary key instead. Does this work out with django?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在直通表上创建复合主键(使用 ALTER TABLE)。您还可以从表中删除 id 列。这些都不会以某种方式损害 django,因为 ManyToMany 字段在后端的工作方式无论如何都不会使用 id 列。
然而你应该注意到,让复合 PK 在 django 中工作基本上是不可能的。这对你来说不应该是一个问题,因为没有表应该有一个外键到你的直通表(至少出于我能想到的任何原因。
所以总之。复合主键不适用于 django。所以如果你曾经需要有一个带有复合 PK 的表的外键,你基本上是 SOL。最后,这里没有真正的优点,但也没有真正的缺点(在这一个也是唯一的情况下)。有时间担心这个吗?
You could create a compound primary key on your through table (with ALTER TABLE). You could also drop the id column from the table. None of this would harm django in way since the way ManyToMany fields work in the backend they wouldn't use the id column anyway.
However you should note that getting compound PK to work in django is basically a non starter. This shouldn't be an issue for you as no table should have a ForeignKey to your through table (for any reason that I can think of at least.
So in summary. Compound primary keys don't work with django. So if you ever need to have a ForeignKey to a table with a compound PK you are basically SOL. Finally there is no real pro about using a compound PK here, but no real con either (in this one and only case). So why are you spending your time worrying about this?