如何添加一个使用sqlalchemy的情况不敏感的独立性?
在某些数据库中,字符串列默认为不敏感(MySQL,SQL Server(,因此您无需做任何其他事情。
在其他情况下,您可以创建一个功能索引,以实施对案例不敏感的独特约束:
Index('myIndex', func.lower(mytable.c.myColumn), unique=True)
,如果数据库支持该列,您还可以为列指定列的不敏感整理。例如,sqlite具有" nocase"整理:
myColumn = Column(String(255), collation='NOCASE', nullable=False)
请参阅http://docs.sqlalchemy.org/en/latest/core/type_basics.html?highlight = collation #sqlalchemy.types.types.string.params.collation.collation
,如果您的数据库提供了合适的数据库,则可以为列指定用户定义的类型。PostgreSQL的CiteXT数据类型对病例不敏感。请参阅https://github.com/mahmoudimus/sqlalchemy-citext
最后,您可以自定义DDL以创建特定数据库的约束。
要添加 @jspcal的答案,如果模型是使用 class
定义的,则在声明model
或使用text
构造后,您必须独立实例化它。
即。
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)
使用文本结构:
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 需要是元组或dict,因此需要在括号内进行拖延逗号。
将以小写形式在表user
的username
列上创建索引。因此,存储在此列中的数据是唯一的,而且情况不敏感。