Django ManyToManyField 关联表必须有代理键吗?
我正在将现有数据库结构映射到 Django 模型中。我有一个多对多结构,其中关联表是自然键控的:
CREATE TABLE foo (id INTEGER PRIMARY KEY);
CREATE TABLE bar (id INTEGER PRIMARY KEY);
CREATE TABLE foo2bar (foo_id INTEGER REFERENCES foo(id),
bar_id INTEGER REFERENCES bar(id),
PRIMARY KEY (foo_id, bar_id)
);
是否没有办法让 Django 的 ORM 来映射它?我必须更改 foo2bar 以使用代理键吗?例如
CREATE TABLE foo2bar (id INTEGER PRIMARY KEY,
foo_id INTEGER REFERENCES foo(id),
bar_id INTEGER REFERENCES bar(id)
);
CREATE UNIQUE INDEX ix_foo2bar_uniq ON foo2bar (foo_id, bar_id);
I'm mapping an existing database structure into Django models. I have a many-to-many structure where the association table is natural-keyed:
CREATE TABLE foo (id INTEGER PRIMARY KEY);
CREATE TABLE bar (id INTEGER PRIMARY KEY);
CREATE TABLE foo2bar (foo_id INTEGER REFERENCES foo(id),
bar_id INTEGER REFERENCES bar(id),
PRIMARY KEY (foo_id, bar_id)
);
Is there no way to get Django's ORM to map this? Must I change foo2bar to use a surrogate key? E.g.
CREATE TABLE foo2bar (id INTEGER PRIMARY KEY,
foo_id INTEGER REFERENCES foo(id),
bar_id INTEGER REFERENCES bar(id)
);
CREATE UNIQUE INDEX ix_foo2bar_uniq ON foo2bar (foo_id, bar_id);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不认为 Django - 就 1.1 而言 - 允许像你想要的复合主键。
请参阅: http://code.djangoproject.com/ticket/373
所以,我想说除非 1.2(2010 年 3 月?)实现上述问题的修复,否则您将必须修改数据库表。
I don't think Django - as far as 1.1 - allows for composite primary keys like you want.
See: http://code.djangoproject.com/ticket/373
So, I would say that unless 1.2 (March 2010?) implements a fix for the ticket above, you will have to modify your database table.