文章内容

2022/2/11 11:11:36,作 者: 黄兵

SQLAlchemy 多个键唯一约束

最近需要对一张表的两个字段唯一性约束,也就是:一个字段可以一样,但是两个字段合在一起就不能一样。

MySQL 多字段联合唯一约束,具体的 SQL 代码如下:

CREATE UNIQUE INDEX 索引名 ON 表名( 字段一, 字段二 );

ALTER TABLE 表名 ADD UNIQUE KEY(字段一, 字段二);

在 SQLAlchemy 模型中,如何定义两个字段唯一约束呢?下面是具体代码示例:

# version1: table definition
mytable = Table('mytable', meta,
    # ...
    Column('customer_id', Integer, ForeignKey('customers.customer_id')),
    Column('location_code', Unicode(10)),

    UniqueConstraint('customer_id', 'location_code', name='uix_1')
    )
# or the index, which will ensure uniqueness as well
Index('myindex', mytable.c.customer_id, mytable.c.location_code, unique=True)


# version2: declarative
class Location(Base):
    __tablename__ = 'locations'
    id = Column(Integer, primary_key = True)
    customer_id = Column(Integer, ForeignKey('customers.customer_id'), nullable=False)
    location_code = Column(Unicode(10), nullable=False)
    __table_args__ = (UniqueConstraint('customer_id', 'location_code', name='_customer_location_uc'),
                     )

上面的代码提供了两种方案,都可以达到一样的效果。


参考资料:

1、sqlalchemy unique across multiple columns


黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - SQLAlchemy 多个键唯一约束

分享到:

发表评论

评论列表