簡體   English   中英

SQLAlchemy 不插入默認值

[英]SQLAlchemy does not insert default values

我有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_atupdated_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).

我看到該行在created_at updated_at列中包含null而不是默認值。

如何自動插入默認值?

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 的,它可用於純文本 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM