sqlachemy UniqueConstraint 有条件吗?

Eri*_*rik 7 python sqlalchemy

是否可以在表上创建约束并在一个或多个列上指定值?考虑这个例子:

mytable = Table('mytable', meta,

    # per-column anonymous unique constraint
    Column('col1', Integer,),
    Column('col2', Integer),
    Column('col3', ENUM('ready', 'pass', 'fail'),

    UniqueConstraint('col2', 'col2', 'col3', name='uix_1')
    )
Run Code Online (Sandbox Code Playgroud)

但我不仅仅想要当 col3 等于“准备好”状态时的唯一性(我想要多次成功或失败)。

    UniqueConstraint('col2', 'col2', 'col3 == ready', name='uix_1')
Run Code Online (Sandbox Code Playgroud)

这在 sqlalchemy api 中可能吗?

Moh*_*asm 12

此链接上有一个完整的示例:

class ExampleTable(Base):

    __tablename__ = 'example_table'
    __table_args__ = (
        Index(
            'ix_unique_primary_content',  # Index name
            'object_type', 'object_id',  # Columns which are part of the index
        unique=True,
        postgresql_where=Column('is_primary')),  # The condition
    )

    id = Column(Integer, primary_key=True)
    object_type = Column(Unicode(50))
    object_id = Column(Integer)
    is_primary = Column(Boolean)
Run Code Online (Sandbox Code Playgroud)

所以你可以使用这样的东西:

Index(
    'col1', 'col2',  # Columns which are part of the index
    unique=True,
    postgresql_where=Column("col3='ready'")),  # The condition
Run Code Online (Sandbox Code Playgroud)