感觉这算 sqlalchemy 使用中的问题
直接使用Enum,不进行Filed:sa_type标注:
在postgresql中会生成一个单独的枚举类型 DemoEnum
(Python) -> demoenum
(postgresql) ,这样性能应该会好(查了下一个枚举值才占4字节),但是在开发期间容易影响效率。修改后,在插入新枚举值会报错:
sqlalchemy.exc.PendingRollbackError: This Session's transaction has been rolled back due to a previous exception during flush. To begin a new transaction with this Session, first issue Session.rollback(). Original exception was: (sqlalchemy.dialects.postgresql.asyncpg.Error) <class 'asyncpg.exceptions.DataError'>: invalid input for query argument $9: <BaseColumnType.select: 'select'> (expected str, got BaseColumnType)
...
(Background on this error at: https://sqlalche.me/e/20/dbapi) (Background on this error at: https://sqlalche.me/e/20/7s2a)
问了下deepseek,修改如下
直接标注sa_type=String(32)会在插入时报错
from enum import Enum
from sqlalchemy import Enum as SQLAlchemyEnum
from sqlmodel import Field, SQLModel
class DemoEnum(Enum):
a = "a"
b = "b"
class DemoModel(SQLModel, table=True):
base_type: DemoEnum = Field(sa_type=SQLAlchemyEnum(DemoEnum, native_enum=False, length=32))