简体   繁体   English

sqlalchemy创建外键?

[英]sqlalchemy create a foreign key?

I have a composite PK in table Strings (integer id, varchar(2) lang) 我在表字符串中有一个复合PK(整数id,varchar(2)lang)

I want to create a FK to ONLY the id half of the PK from other tables. 我想创建一个FK,使其仅包含来自其他表的PK的id一半。 This means I'd have potentially many rows in Strings table (translations) matching the FK. 这意味着在字符串表(翻译)中可能有许多行与FK匹配。 I just need to store the id, and have referential integrity maintained by the DB. 我只需要存储ID,并由数据库维护引用完整性。

Is this possible? 这可能吗? If so, how? 如果是这样,怎么办?

This is from wiki 这是来自维基

The columns in the referencing table must be the primary key or other candidate key in the referenced table. 引用表中的列必须是引用表中的主键或其他候选键。 The values in one row of the referencing columns must occur in a single row in the referenced table. 引用列的一行中的值必须出现在引用表的一行中。

Let's say you have this: 假设您有以下内容:

id | var            
1  |  10            
1  |  11          
2  |  10

The foreign key must reference exactly one row from the referenced table. 外键必须精确地引用引用表中的一行 This is why usually it references the primary key. 这就是为什么它通常引用主键的原因。

In your case you need to make another Table1(id) where you stored the ids and make the column unique/primary key. 在您的情况下,您需要制作另一个存储ID的Table1(id),并使列唯一/主键。 The id column in your current table is not unique - you can't use it in your situation... so you make a Table1(id - primary key) and make the id in your current table a foreign key to the Table1 . 当前表中的id列不是唯一的-不能在您的情况下使用它...因此,您需要创建Table1(id-主键) ,并将当前表中的id用作Table1的外键 Now you can create foreign keys to id in Table1 and the primary key in your current table is ok. 现在,您可以在Table1中创建ID的外键,并且当前表中的主键正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM