Skip to content Skip to sidebar Skip to footer

Sqlachemy Uniqueconstraint With Conditional?

Is it possible to create a contraint on a table and specify a value on one or more of the columns? Condsider this example: mytable = Table('mytable', meta, # per-column anonym

Solution 1:

There is a full example on this 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)

so you can use something like this:

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

Solution 2:

So from what I understand you want the group (col1, col2, col3) to be unique only if col3 has the value 'ready'?

I don't think that is possible using unique constraints. It could be done with a CheckConstraint, assuming your database supports it.

You can read up on it here

Post a Comment for "Sqlachemy Uniqueconstraint With Conditional?"