How to add UniqueConstraint in SQLAlchemy

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

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

2条回答
  •  野的像风
    2021-01-14 05:32

    In some databases, string columns are case-insensitive by default (MySQL, SQL Server), so you wouldn't need to do anything extra.

    In others, you can create a functional index that enforces the case-insensitive unique constraint:

    Index('myIndex', func.lower(mytable.c.myColumn), unique=True)
    

    You can also specify a case-insensitive collation for the column if the database supports it. For instance SQLite has a 'NOCASE' collation:

    myColumn = Column(String(255), collation='NOCASE', nullable=False)
    

    See http://docs.sqlalchemy.org/en/latest/core/type_basics.html?highlight=collation#sqlalchemy.types.String.params.collation

    You may also specify a user-defined type for your column if your database provides a suitable one. PostgreSQL has a citext data type which is case-insensitive. See https://github.com/mahmoudimus/sqlalchemy-citext

    Finally you can customize the DDL to create the constraint for your specific database.

提交回复
热议问题