英文:
SQLAlchemy syntax for GENERATED ALWAYS AS IDENTITY on postgres database
问题
以下是代码部分的翻译,不包括问题的回答:
class X(Base):
__tablename__ = "x"
x_id = Column(Integer, primary_key=True, server_default=text("GENERATED ALWAYS AS IDENTITY"))
x_name = Column(Text, unique=True)
这里的关键是在x_id
列上使用server_default
参数,并将其设置为GENERATED ALWAYS AS IDENTITY
。这将确保生成的SQL中使用正确的语法。
英文:
How could the following table be represented as an SQLA model?
CREATE TABLE x
(
x_id integer GENERATED ALWAYS AS IDENTITY,
x_name text unique
);
I think that if I create a column using:
id = Column(Integer, nullable=False, primary_key=True)
The generated SQL won't use GENERATED ALWAYS AS IDENTITY
, but will instead use SERIAL
.
Completing the following, in order to use the GENERATED ALWAYS AS IDENTITY
syntax, is what I'm unsure of:
class X(Base):
__tablename__ = "x"
x_id = Column( <something here> )
x_name = Column(Text, unique = True)
答案1
得分: 2
你可以在列定义中使用 Identity
。
class X(Base):
__tablename__ = "x"
x_id = Column(Integer, Identity(always=True), primary_key=True)
x_name = Column(Text, unique=True)
PS. 如果你设置了 primary_key=True
,则不需要设置 nullable=False
。
英文:
You can use an Identity
in your column definition.
class X(Base):
__tablename__ = "x"
x_id = Column(Integer, Identity(always=True), primary_key=True)
x_name = Column(Text, unique=True)
PS. no need to set nullable=False
if you set primary_key=True
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论