具有外键约束的复合主键(2列)到2个表,添加更多约束

时间:2016-10-30 13:36:47

标签: python sqlalchemy

我正在尝试对以下SQLAlchemy模型进行建模。

Block -> (pk-block_id, ...)
Floor -> (pk-floor_id, fk-block_id, ...)
Number -> (pk-number_id, fk-block_id, ...)
Unit -> (pk-fk-floor_id, pk-fk-number_id, ...)

Unit有一个复合主键,由(floor_id, number_id)个外键组成。

我想进一步限制UnitUnit.floor.block_id == Unit.number.block_id的外键。

我怎么能模仿这样的东西?以下是伪代码。

class Block(Base):
    id = Column(Integer, primary_key=True)

class Floor(Base):
    id = Column(Integer, primary_key=True)
    block_id = Column(Integer, ForeignKey('blocks.id'))

class Number(Base):
    id = Column(Integer, primary_key=True)
    block_id = Column(Integer, ForeignKey('blocks.id'))

class Unit(Base):
    floor_id = Column(Integer, primary_key=True)
    number_id = Column(Integer, primary_key=True)

    __table_args__ = (
        ForeignKeyConstraint(
            [floor_id, number_id],
            ['floors.id', 'numbers.id']
            ),
        )
    # FIXME: Want to constraints Unit.floor.block_id == Unit.number.block_id

谢谢!

0 个答案:

没有答案