gpt4 book ai didi

sqlalchemy - 如何在 Alembic 中创建 postgresql 的序列

转载 作者:行者123 更新时间:2023-12-02 11:28:04 33 4
gpt4 key购买 nike

我正在使用alembic维护我的 table 。同时,我使用声明式方式更新我的模型。

这是蒸馏器的一张 table :

op.create_table(
'groups',
Column('id', Integer, Sequence('group_id_seq'), primary_key=True),
Column('name', Unicode(50)),
Column('description', Unicode(250)),
)

模型如下:

class Group(Base):
__tablename__ = 'groups'
id = Column(Integer, Sequence('group_id_seq'), primary_key=True)
name = Column(Unicode(50))
description = Column(Unicode(250))

def __init__(self, name, description):
self.description = description
self.name = name

你可以看到,我正在使用 Sequence在 Alembic 迁移和声明性模型中。

但我注意到,当使用 PostgreSQL (v9.1) 时,alembic 不会创建任何序列,因此模型无法创建实例,因为它们将使用 nextval(<sequence name>)条款。

那么,如何创建 Alembic 迁移以便在 postgresql 中真正生成序列?

最佳答案

只需将以下内容添加到您的模型中:

field_seq = Sequence('groups_field_seq')
field = Column(Integer, field_seq, server_default=field_seq.next_value())

并将以下内容添加到您的迁移文件中(在创建表之前):

from sqlalchemy.schema import Sequence, CreateSequence
op.execute(CreateSequence(Sequence('groups_field_seq')))

关于sqlalchemy - 如何在 Alembic 中创建 postgresql 的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17196234/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com