【发布时间】:2016-08-13 09:03:19
【问题描述】:
我想对列强制执行唯一约束,但前提是它不为空。这是 SQLite 中的默认行为,但在 MS SQL Server 中不是。
似乎在 SQL Server 中实现此目的的方法是使用带有 where 子句的索引,如 this post 中所述。我的问题是我如何在 SQLAlchemy 中做到这一点,并让它仍然适用于 SQLite。
我想这大概就是我想要的:
class MyClass(Base):
__tablename__ = 'myclass'
__table_args__ = (Index('unique_index', <where clause?>, unique=True)
my_column = Column(Integer) # The column I want unique if not null
其中<where clause?> 是一些将索引放在my_column 上的表达式,而不是NULL。通过阅读索引的documentation 似乎可以做到这一点,但我不知道我需要什么表达式。非常感谢您提供有关此方法或其他方法的帮助。
【问题讨论】:
-
目前
sqlalchemy不支持开箱即用。但我认为值得在 sqlalchemy bitbucket 存储库上创建一个new issue,甚至更好地实现它。我认为它的实现应该类似于其他 RDBMS 特定参数,例如mssql_includeandmssql_clustered。
标签: python sql-server sqlalchemy