在Postgres上使用sqlalchemy创建部分唯一索引 [英] Creating partial unique index with sqlalchemy on Postgres

查看:116
本文介绍了在Postgres上使用sqlalchemy创建部分唯一索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

SQLAlchemy支持在Postgresql中创建部分索引

SQLAlchemy supports creating partial indexes in postgresql.

是否可以创建局部唯一索引

Is it possible to create a partial unique index through SQLAlchemy?

像这样想象一个表/模型:

Imagine a table/model as so:

class ScheduledPayment(Base):
     invoice_id = Column(Integer)
     is_canceled = Column(Boolean, default=False)

我想要一个唯一的索引

我可以在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屋!

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