Python-PostgreSQL主键自动填充报错:SAWarning: Column x is marked as a member of the primary key for table x', but has no Python-side or server-side default generator indicated...
import datetime
from sqlalchemy import Column, String, inspect, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
engine = create_engine(DATABASE_URL)
Base = declarative_base()
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
class Post(Base):
__tablename__ = "post"
id = Column(UUID, primary_key=True, index=True, autoincrement=False)
time = Column(String)
title = Column(String)
content = Column(String)
username = Column(String)
def create_post(post: dict) -> bool:
db = SessionLocal()
try:
post = Post(data=post)
db.add(post)
db.commit()
return True
finally:
db.close()
time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
create_post({"title": "test", "content": "test", "username": "admin", 'time': time})
测试数据库接口是否正常时发生报错:
SAWarning: Column 'post.id' is marked as a member of the primary key for table 'post', 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.
在PostgreSQL内,
- Primary key = id,
- Data type = uuid,
- Deafult = gen_random_uuid(),
并且数据类里也设置了 autoincrement=False,还是发生报错。经过尝试,发现:即使设置了默认填充的id,还是需要在后端这里指定:
id = Column(UUID(), primary_key=True, server_default=text("uuid_generate_v4()"))
顺利解决!
运行环境
PostgreSQL 16.2, compiled by Visual C++ build 1937, 64-bit
sqlalchemy~=2.0.30