How to add UniqueConstraint in SQLAlchemy

后端 未结 2 1055
再見小時候
再見小時候 2021-01-14 05:06

How does one add a UniqueConstraint which is Case Insensitive using SQLalchemy?

2条回答
  •  独厮守ぢ
    2021-01-14 05:35

    To add upon @jspcal's answer, if the model is defined using a class, then one you would have to either instantiate it independently after declaring the model or use the text construct.

    i.e.

    from sqlalchemy.sql.expressions import func
    
    class User(Base):
        __tablename__ = 'user'
        username = Column('username', String(24), nullable=False)
        
    Index('user_username_index', func.lower(User.username), unique=True)
    

    using the text construct:

    from sqlalchemy.sql.expressions import text
    
    class User(Base):
        __tablename__ = 'user'
        __table_args__ = (
            Index('ix_user_name', text('LOWER(username)')), 
        )
        username = Column('username', String(24), nullable=False)
        
    

    NB: table_args needs to be a tuple or dict, hence the need for that trailing comma inside the parenthesis.

    That will create an index on username column of table user in lowercase form. Therefore, data stored in this column is unique and case insensitive.

提交回复
热议问题