如何在SQLAlchemy中添加UniqueConstraint [英] How to add UniqueConstraint in SQLAlchemy

查看:802
本文介绍了如何在SQLAlchemy中添加UniqueConstraint的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用SQLalchemy添加不区分大小写的UniqueConstraint?

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

推荐答案

在某些数据库中,字符串列区分大小写-默认情况下不敏感(MySQL,SQL Server),因此您无需执行任何其他操作。

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)

如果数据库支持,还可以为列指定不区分大小写的排序规则。例如,SQLite具有'NOCASE'排序规则:

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)

请参见 http://docs.sqlalchemy.org/en/latest/core/type_basics.html?highlight = collat​​ion#sqlalchemy.types.String.params.collat​​ion

如果数据库提供了合适的类型,您也可以为列指定用户定义的类型。 PostgreSQL具有不区分大小写的citext数据类型。参见 https://github.com/mahmoudimus/sqlalchemy-citext

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

最后,您可以自定义DDL为特定数据库创建约束。

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

这篇关于如何在SQLAlchemy中添加UniqueConstraint的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆