Sqlalchemy Core 使用 UniqueConstraint 和条件创建表

问题描述 投票:0回答:2

数据库=postgresql

有一个使用此语法创建的表

event_invites = Table(
    "event_invites",
    metadata,
    Column("id", Integer(), primary_key=True),
    Column("from_user", ForeignKey(users.c.id, ondelete="SET NULL"), nullable=False),
    Column("to_user", ForeignKey(users.c.id, ondelete="SET NULL"), nullable=False),
    Column("to_event", ForeignKey(events.c.id, ondelete="CASCADE"), nullable=False),
    Column(
        "is_active",
        Boolean(),
        server_default=sql.expression.true(),
        nullable=True,
    ),
    ....
    ....
    UniqueConstraint('from_user', 'to_user', 'to_event', 'is_active', name='unique_event_invites')
)

我需要添加它,以便仅当

is_active
字段为
True
时才会触发字段的唯一性。

我找到了一种在使用 Sqlalchemy ORM 语法创建表时添加此条件的方法

示例

class ExampleTable(Base):

    __tablename__ = 'example_table'
    __table_args__ = (
        Index(
            'ix_unique_primary_content',  # Index name
            'object_type', 'object_id',  # Columns which are part of the index
        unique=True,
        postgresql_where=Column('is_primary')),  # The condition
    )

    id = Column(Integer, primary_key=True)
    object_type = Column(Unicode(50))
    object_id = Column(Integer)
    is_primary = Column(Boolean)

但我不知道如何适应我的情况

类似这样的事情

UniqueConstraint('from_user', 'to_user', 'to_event', 'is_active', name='unique_event_invites',
                 postgresql_where=Column("is_active=True")
                 )

返回错误

sqlalchemy.exc.ArgumentError: Argument 'postgresql_where' is not accepted by dialect 'postgresql' on behalf of <class 'sqlalchemy.sql.schema.UniqueConstraint'>
python-3.x postgresql sqlalchemy
2个回答
0
投票

使用 Index 和 unique=True

event_invites = Table(
    "event_invites",
    metadata,
    Column("id", Integer(), primary_key=True),
    Column("from_user", ForeignKey(users.c.id, ondelete="SET NULL"), nullable=False),
    Column("to_user", ForeignKey(users.c.id, ondelete="SET NULL"), nullable=False),
    Column("to_event", ForeignKey(events.c.id, ondelete="CASCADE"), nullable=False),
    Column(
        "is_active",
        Boolean(),
        server_default=sql.expression.true(),
        nullable=True,
    ),
    ....
    ....
        Index("unique_event_invites", "from_user", "to_user", "to_event", "is_active", unique=True,
          postgresql_where=Column("is_active='True'"))
)

0
投票

此语法类似于 @jekson 响应,对我使用 SQLAlchemy 2.0 有效:

Index("unique_event_invites",
      "from_user", "to_user", "to_event", "is_active",
      unique=True,
      postgresql_where=(is_active==True))

请注意

Column
参数中缺少
postgresql_where
类型,并且直接在表达式中使用字段
is_active

© www.soinside.com 2019 - 2024. All rights reserved.