列被标记为表主键的成员,但并没有Python端或服务器端的默认生成器
这是我正在做的一张桌子:列被标记为表主键的成员,但并没有Python端或服务器端的默认生成器,python,postgresql,sqlalchemy,Python,Postgresql,Sqlalchemy,这是我正在做的一张桌子: URL = 'postgresql://{}:{}@{}:{}/{}' DB_URL = URL.format( DB_USER_NAME, DB_PASSWORD, DB_HOST, str(DB_PORT), DB_NAME) print("creating db engine...") # Connect to database CONN = create_engine(DB_URL, client_
URL = 'postgresql://{}:{}@{}:{}/{}'
DB_URL = URL.format(
DB_USER_NAME,
DB_PASSWORD,
DB_HOST,
str(DB_PORT),
DB_NAME)
print("creating db engine...")
# Connect to database
CONN = create_engine(DB_URL, client_encoding="UTF-8")
META_DATA = MetaData(bind=CONN, reflect=True)
print("creating users table")
TABLE_EXISTS = CONN.dialect.has_table(CONN, "users")
USERS_TABLE = None
# Create tables
if not TABLE_EXISTS:
USERS_TABLE = \
Table("test_user", META_DATA,
Column("id", Integer, Sequence("user_id_seq"), primary_key=True),
Column("first_name", String(255)),
Column("last_name", String(255))
)
META_DATA.create_all(CONN)
else:
USERS_TABLE = Table("test_user", META_DATA, autoload=True)
if USERS_TABLE != None:
print("done")
else:
raise Exception("Halp")
# Insertions
INS_EXPRESSION = USERS_TABLE.insert(None).values(first_name="Foo", last_name="Bar")
CONN.execute(INS_EXPRESSION)
# Selections
SELECTION = select([USERS_TABLE])
RESULT = CONN.execute(SELECTION)
for row in RESULT:
print(row)
当我运行这段代码并进行插入时,它第一次工作。但如果我第二次运行它,就会出现以下错误:
SAWarning: Column 'test_user.id' is marked as a member of the primary key for table 'test_user', but has no Python-side or server-side default generator indicated, nor does it indicate 'autoincrement=True' or 'nullable=True', and no explicit value is passed. Primary key columns typically may not store NULL.
失败的行记录为:
DETAIL: Failing row contains (null, Foo, Bar).
我做错了什么???不必手动处理序列中的自动递增主键,只需将
autoincrement=True
传递到列('id',…)
(并删除序列)。除非你一定要有一个名为user_id_seq的序列。我刚刚弄明白了。。。我不知道为什么序列是可选的,但是…它至少在那里。