Skip to main content
 首页 » 编程设计

python之sqlalchemy.exc.InvalidRequestError : SQL expression, 列,或预期的映射实体

2025年05月04日7zhengyun_ustc

我遇到了这个我无法理解的 sqlachemy 错误:

sqlalchemy.exc.InvalidRequestError: SQL expression, column, or mapped entity expected - got '<class '__main__.JobRecord'>' 

这个错误是什么意思?可能的原因是什么?

这是触发错误的方法:

@classmethod 
def find_job_record_from_pk(cls, pk): 
    ''' 
    return the job record with the given pk 
    ''' 
    job_record = MlcDb.get_session().query(cls).filter(cls.pk == pk).first() 
    return job_record  

映射:

@classmethod 
def define_mapping(cls): 
    ''' 
    SQLAlchemy mapping definition 
    ''' 
    cls.mapper = mapper(cls, cls.table,  
        polymorphic_on = cls.table.c.item_type,  
        properties = { 
            'item_type': synonym('_JobRecord__item_type', map_column=True), 
            'version': synonym('_JobRecord__version', map_column=True), 
            'state': synonym('_JobRecord__state', map_column=True), 
            'date_created' : synonym( '_JobRecord__date_created', map_column=True) 
        } 
    ) 

请您参考如下方法:

在我的例子中,错误发生是因为我忘记从类定义中的“Base”扩展。 根据给定的错误,它很可能被声明为 如下:

JobRecord: 
     pro1: Column() 
 

代替

from sqlalchemy.ext.declarative import declarative_base 
Base = declarative_base() 
JobRecord(Base): #here is the missing extend 
     pro1: Column() 

消息说“无法识别该参数。”

根据文档

Classes mapped using the Declarative system are defined in terms of a base class which maintains a catalog of classes and tables relative to that base - this is known as the declarative base class

重要的是要注意:

Our application will usually have just one instance of this base in a commonly imported module. We create the base class using the declarative_base() function

当然,所有这些对我的特殊情况都有帮助

我希望这是有用的。

更多信息: https://docs.sqlalchemy.org/en/13/orm/tutorial.html