在多个外键上组合唯一键

时间:2017-02-08 00:21:36

标签: sqlalchemy flask-sqlalchemy

鉴于这些SQLAlchemy模型:

class Key():
    key_id = Column('id', Integer, primary_key=True, autoincrement=True)
    name = Column(String(255))

class House():
    house_id = Column('id', Integer, primary_key=True, autoincrement=True)
    name = Column(String(255))

class HouseKey():
    house_key_id = Column('id', Integer, primary_key=True, autoincrement=True)
    house_id = Column(Integer, ForeignKey('house.id'))
    key_id = Column(Integer, ForeignKey('key.id'))

    UniqueConstraint('house_id', 'key_id')

    house = relationship('House', foreign_keys=[house_id])
    key = relationship('Key', foreign_keys=[key_id])

未创建house_id, key_id唯一键。我相信this就是为什么(如果我错了,请纠正我。)

如何在也是外键的列上创建复合唯一键?

1 个答案:

答案 0 :(得分:1)

表级UNIQUE限制符合__table_args__

class HouseKey(Base):
    ...
    __table_args__ = (UniqueConstraint("house_id", "key_id"),)