在 Postgres 上使用 sqlalchemy 创建部分唯一索引 [英] Creating partial unique index with sqlalchemy on Postgres
本文介绍了在 Postgres 上使用 sqlalchemy 创建部分唯一索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
SQLAlchemy 支持在 postgresql 中创建部分索引.
SQLAlchemy supports creating partial indexes in postgresql.
是否可以创建部分<强>唯一索引通过SQLAlchemy?
Is it possible to create a partial unique index through SQLAlchemy?
想象一个表格/模型:
class ScheduledPayment(Base):
invoice_id = Column(Integer)
is_canceled = Column(Boolean, default=False)
我想要一个唯一的索引,其中对于给定的发票只能有一个活动"的 ScheduledPayment.
I'd like a unique index where there can be only one "active" ScheduledPayment for a given invoice.
我可以在 postgres 中手动创建:
I can create this manually in postgres:
CREATE UNIQUE INDEX only_one_active_invoice on scheduled_payment
(invoice_id, is_canceled) where not is_canceled;
我想知道如何使用 SQLAlchemy 0.9 将其添加到我的 SQLAlchemy 模型中.
I'm wondering how I can add that to my SQLAlchemy model using SQLAlchemy 0.9.
推荐答案
class ScheduledPayment(Base):
id = Column(Integer, primary_key=True)
invoice_id = Column(Integer)
is_canceled = Column(Boolean, default=False)
__table_args__ = (
Index('only_one_active_invoice', invoice_id, is_canceled,
unique=True,
postgresql_where=(~is_canceled)),
)
这篇关于在 Postgres 上使用 sqlalchemy 创建部分唯一索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文