简体   繁体   English

在sqlalchemy中复合两个外键?

[英]composite two foreign key in sqlalchemy?

I am using SQLALchemy in flask. 我在烧瓶中使用SQLALchemy。 And I am confused how to define composite key with two foreign keys. 我很困惑如何用两个外键定义组合键。 One foreign key from one table and second from another table. 一个表中的一个外键,另一表中的一个外键。

class Store_category_mapping(db.Model):

    __tablename__ = 'store_category_mapping' 
    category_id = db.Column(db.Integer, nullable=False) 
    store_id = db.Column(db.Integer, nullable=False)
    store_name    = db.Column(db.String(50),  nullable=False)

    __table_args__ = (
        db.ForeignKeyConstraint(
            [category_id, store_id],
            [Category_master.category_id, Store_master.store_id]
        ),
        )

It gives this error: 它给出了这个错误:

sqlalchemy.exc.ArgumentError: ForeignKeyConstraint on store_category_mapping(category_id, store_id) refers to multiple remote tables: category_master and store_master sqlalchemy.exc.ArgumentError:store_category_mapping(category_id,store_id)上的ForeignKeyConstraint引用了多个远程表:category_master和store_master

You can't have a composite foreign key that references more than one remote table. 您不能有一个引用多个远程表的复合外键。 Composite foreign keys are a way to ensure integrity when one remote table has a composite primary key. 复合外键是一种确保远程表具有复合主键的完整性的方法。

If you want to make sure that you only ever have one store_category_mapping entry with a given combination of category_id and store_id you could go for a UniqueConstraint instead. 如果要确保只有一个store_category_mapping条目具有给定的category_idstore_id组合,则可以改用UniqueConstraint

I'm not familiar with flask, but I assume it would look somewhat like this: 我对烧瓶不熟悉,但是我认为它看起来像这样:

class Store_category_mapping(db.Model):

    __tablename__ = 'store_category_mapping' 
    category_id = db.Column(db.Integer, db.ForeignKey(Category_master.category_id), nullable=False) 
    store_id = db.Column(db.Integer, db.ForeignKey(Store_master.store_id), nullable=False)
    store_name    = db.Column(db.String(50),  nullable=False)

    __table_args__ = (
        db.UniqueConstraint('category_id','store_id'),
        )

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

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