FastAPI运行报错:SQLAlchemy无法为dtabelle表组装主键列
解决SQLAlchemy主键组装错误:DTabelle表无主键问题
运行FastAPI应用时触发如下错误:
sqlalchemy.exc.ArgumentError: Mapper mapped class DTabelle->dtabelle could not assemble any primary key columns for mapped table 'dtabelle'删除
d_tabelle.py文件后应用可正常运行,对比其他正常工作的OTabelle、VTabelle模型,未发现明显结构差异,但问题仅出现在DTabelle上。
问题根源
查看d_tabelle.py代码就能发现:DTabelle这个表模型类仅继承了SQLModel,没有继承定义了主键字段的DTabelleBase。而其他正常工作的模型(如OTabelle、VTabelle)都是继承了对应的Base类+table=True,从而能将Base类中的字段(包括主键)纳入表结构。
修复方法
修改d_tabelle.py中的DTabelle类,让它继承DTabelleBase:
class DTabelle(DTabelleBase, table=True): rel_t_tabelle_t_id: Union[TTabelle, None] = Relationship(back_populates='rel_d_tabelle_t_id', sa_relationship_kwargs={'primaryjoin': 'TTabelle.t_id==DTabelle.t_id'})
修复原理
修改后,DTabelle会自动继承DTabelleBase中的所有字段,包括标记为primary_key=True的d_id,SQLAlchemy就能正常识别表的主键结构,不会再抛出错误,应用可正常启动。
内容的提问来源于stack exchange,提问作者Emil
相关产品推荐
相关产品推荐

