【问题标题】:sqlachemy UniqueConstraint with conditional? [duplicate]sqlalchemy 有条件的唯一约束? [复制]
【发布时间】:2018-08-23 14:28:23
【问题描述】:

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

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')
    )

但我不只希望 col3 等于“就绪”状态(我希望多次成功或失败)时的唯一性。

    UniqueConstraint('col2', 'col2', 'col3 == ready', name='uix_1')

这在 sqlalchemy api 中可行吗?

【问题讨论】:

标签: python sqlalchemy


【解决方案1】:

这个link有一个完整的例子:

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)

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

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

【讨论】:

  • 可以通过Indexunique=True 一起执行唯一性,就像通过使用UniqueConstraint 一样?
  • 添加此索引后,我仍然可以添加重复的行。我做错了什么?
  • @MarkMishyn 我认为这是数据库级别的检查。你确定你在创建表时有这个索引(unique=True)吗?我建议检查该索引是否正确存在于表架构中 (postgresqltutorial.com/postgresql-describe-table)。
  • @Mohsenasm 谢谢,我会检查的。
【解决方案2】:

所以据我了解,您希望组 (col1, col2, col3) 只有在 col3 的值为 'ready' 时才唯一?

我认为使用唯一约束是不可能的。假设您的数据库支持它,可以使用 CheckConstraint 来完成。

您可以阅读它here

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 2021-10-12
    • 2015-11-06
    • 2013-04-20
    • 2021-07-22
    • 2017-07-07
    • 1970-01-01
    • 2016-08-22
    相关资源
    最近更新 更多