SQLAlchemy多态问题:出现“No such polymorphic_identity 0 is defined”错误
解决SQLAlchemy "No such polymorphic_identity 0 is defined" 错误
问题根源
你代码里的核心冲突是:
- 基类
User的type字段是Integer类型,但polymorphic_identity用了字符串值('user'、'patient') - 查询时SQLAlchemy从数据库读取到
type的整数值(比如0),但找不到对应字符串类型的polymorphic标识,因此报错。
修复步骤
1. 统一polymorphic_identity的类型与字段类型
将基类和派生类的polymorphic_identity改为整数,和type字段类型匹配:
修改后的基类代码
class User(Base): id = Column(Integer, primary_key=True, index=True) email = Column(String, nullable=False, unique=False, index=True) # TODO unique=True password = Column(String, nullable=False) birthdate = Column(DateTime, nullable=False) is_superuser = Column(Boolean(), default=False) is_active = Column(Boolean(), default=True) type = Column(Integer, nullable=False) # Inheritance __mapper_args__ = { 'polymorphic_identity': 0, # 改为整数,对应普通用户 'polymorphic_on': 'type' # 仅基类需要定义polymorphic_on }
修改后的派生类代码
class Patient(User): id = Column(Integer, ForeignKey('user.id', ondelete="CASCADE"), primary_key=True) patient_id = Column(String, nullable=False) # Inheritance __mapper_args__ = { 'polymorphic_identity': 1, # 改为整数,对应患者用户 # 派生类无需重复定义polymorphic_on } # Relationships docs = relationship("Document", back_populates="patient")
2. 同步数据库数据
如果数据库中已有数据,需要确保user表的type字段值和你设置的polymorphic_identity一致:
- 普通用户的
type设为0 - 患者用户的
type设为1
可以执行SQL语句更新:
UPDATE user SET type = 0 WHERE type IS NULL OR type NOT IN (0,1); UPDATE user u JOIN patient p ON u.id = p.id SET u.type = 1;
3. 验证查询
重新执行你的查询代码:
users = db.query(User) print(users.statement) print(f"Count is {users.count()}") user = users.first()
额外建议(可选)
如果想让类型更清晰,推荐使用SQLAlchemy的Enum类型定义type字段,避免硬编码整数:
from sqlalchemy import Enum class UserType(Enum): USER = 0 PATIENT = 1 class User(Base): # ... 其他字段 type = Column(Enum(UserType), nullable=False) __mapper_args__ = { 'polymorphic_identity': UserType.USER, 'polymorphic_on': 'type' } class Patient(User): # ... 其他字段 __mapper_args__ = { 'polymorphic_identity': UserType.PATIENT }
内容的提问来源于stack exchange,提问作者William Bob
相关产品推荐
相关产品推荐

