postgresql 为什么 sqlalchemy 的默认列值不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20348801/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 01:13:05  来源:igfitidea点击:

Why isn't sqlalchemy's default column value working

pythonpostgresql

提问by Aylwyn Lake

I am using Postgresql 9.1 and SQLAlchemy 0.9.

我使用的是 Postgresql 9.1 和 SQLAlchemy 0.9。

The problem is, 'default=10' doesn't work.

问题是,“ default=10”不起作用。

My Code:

我的代码:

conn_str = 'postgresql://test:pass@localhost/test'
engine = create_engine(conn_str)
metadata = MetaData(bind=engine)

cols=[]
cols += [Column('Name', VARCHAR(20), primary_key=True, nullable=False)]
cols += [Column('age', INT, default=10, nullable=False )]
Table('t1', metadata, *cols)
metadata.create_all(engine)

psql:

psql:

test=> \dS t1
            Table "public.t1"
Column |         Type          | Modifiers
--------+-----------------------+-----------
Name   | character varying(20) | not null
age    | integer               | not null
Indexes:
    "t1_pkey" PRIMARY KEY, btree ("Name")

I tried with an SQL statement directly and it should look like:

我直接尝试使用 SQL 语句,它应该如下所示:

test=> \dS t2
              Table "public.t2"
 Column |         Type          | Modifiers
--------+-----------------------+------------
 Name   | character varying(10) | not null
 age    | integer               | default 10
Indexes:
    "t2_pkey" PRIMARY KEY, btree ("Name")

What am I doing wrong?

我究竟做错了什么?

回答by tbischel

instead of using default, use server_default... fixed the problem for me https://docs.sqlalchemy.org/en/latest/core/defaults.html?highlight=schema%20column#sqlalchemy.schema.ColumnDefault

而不是使用默认值,使用 server_default ... 为我解决了这个问题 https://docs.sqlalchemy.org/en/latest/core/defaults.html?highlight=schema%20column#sqlalchemy.schema.ColumnDefault