我有workspaces桌子
workspaces_table = Table(
"workspaces", metadata_obj,
Column("id", UUID(as_uuid=False), primary_key=True, default=uuid.uuid4),
Column("name", JSONB(), nullable=False),
Column("created_at", TIMESTAMP(timezone=False), default=datetime.datetime.now(), nullable=False),
Column("updated_at", TIMESTAMP(timezone=False), default=datetime.datetime.now(), nullable=False),
Column("created_by", UUID(as_uuid=False), ForeignKey('users.id'), nullable=False),
Column("updated_by", UUID(as_uuid=False), ForeignKey('users.id'), nullable=False),
Column("email", Text(), nullable=False)
)
在此表列中created_at并updated_at具有默認值datetime.datetime.now()
但是當我嘗試在這個表中插入行時
await conn.execute(text(
f"""
WITH workspace_create AS (
INSERT INTO workspaces(id, name, created_by, updated_by, email)
VALUES (:workspace_id, :workspace_name, :user_id, :user_id, :workspace_email)
),
workspace_roles_create AS (
INSERT INTO workspace_roles(id, name, export_data, users, settings, projects, roles, system_name,
workspace_id)
VALUES {sql_query_workspace_roles_values}
)
INSERT INTO m2m_users_to_workspace_or_project_roles(user_id, role_id, role_type, user_status)
VALUES(:user_id, :superuser_id, '{RoleTypes.Workspace.name}', '{UserStatuses.Active.name}')
"""
), params
)
我收到以下錯誤:
null value in column "created_at" of relation "workspaces" violates not-null constraint
DETAIL: Failing row contains (dd31dfb6-6d22-4794-b804-631e60b6e063, [{"locale": "ru", "text_value": "ru_team_1"}], null, null, 481b7a55-52b7-48f2-89ea-4ae0673d4ab6, 481b7a55-52b7-48f2-89ea-4ae0673d4ab6, ruslpogo@gmail.com).
我看到該行包含列中null的默認值created_at updated_at。
如何自動插入默認值?
uj5u.com熱心網友回復:
Column(…, default=…)是 SQLAlchemy Core(和 SQLAlchemy ORM)在執行類似workspaces_table.insert(). 請注意,如果 SQLAlchemy 創建表,則該列沒有服務器端 DEFAULT:
workspaces_table = Table(
"workspaces",
MetaData(),
Column("id", Integer(), primary_key=True),
Column("created_at", DateTime(), default=datetime.now()),
)
engine.echo = False
workspaces_table.drop(engine, checkfirst=True)
engine.echo = True
workspaces_table.create(engine)
""" DDL emitted:
CREATE TABLE workspaces (
id SERIAL NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE,
PRIMARY KEY (id)
)
"""
Column(…, server_default=…)是指定服務器端 DEFAULT 的內容,該服務器端 DEFAULT 可用于純文本 INSERT 陳述句,例如您的問題中的陳述句:
workspaces_table = Table(
"workspaces",
MetaData(),
Column("id", Integer(), primary_key=True),
Column("created_at", DateTime(), server_default=text("CURRENT_TIMESTAMP")),
)
engine.echo = False
workspaces_table.drop(engine, checkfirst=True)
engine.echo = True
workspaces_table.create(engine)
""" DDL emitted:
CREATE TABLE workspaces (
id SERIAL NOT NULL,
created_at TIMESTAMP WITHOUT TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
)
"""
請注意,將定義Table()從更改default=為server_default=不會更新現有表;你需要使用它。ALTER TABLE
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/484627.html
標籤:Python sql PostgreSQL sqlalchemy
