Skip to main content
 首页 » 编程设计

python之如何解决 sqlalchemy.orm.exc.UnmappedInstanceError

2024年12月31日25daizhj

我正在为 MYSQL 数据库使用 Python Sqlalchemy。我编写了以下脚本来创建类对象,然后在表中添加一行。

from sqlalchemy import create_engine, MetaData, Table, Column, ForeignKey 
from sqlalchemy.dialects.mysql.base import VARCHAR, LONGTEXT, INTEGER 
from sqlalchemy.orm import sessionmaker 
from sqlalchemy.ext.declarative import declarative_base 
 
engine = create_engine("mysql+mysqldb://root:@localhost/mydb") 
connection = engine.connect() 
 
Session = sessionmaker(bind=engine) 
session = Session() 
Base = declarative_base() 
metadata = MetaData() 
 
class User(Base): 
    __tablename__ = 'User' 
    __abstract__ = True 
    id = Column('id', INTEGER(display_width=11), primary_key=True, nullable=False) 
    email = Column('email', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=100), unique=True) 
    password = Column('password', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=45)) 
    name = Column('name', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=100)) 
 
Base.metadata.create_all(engine) 
 
add_user = User(email = "testing@testing.com", 
            password = 'testing', 
            name = 'testing') 
session.add(add_user) 
session.commit() 

当我尝试添加到 session 时,它会抛出以下错误:

 AttributeError: 'User' object has no attribute '_sa_instance_state' 
 
 During handling of the above exception, another exception occurred: 
 
 raise exc.UnmappedInstanceError(instance) 
 sqlalchemy.orm.exc.UnmappedInstanceError: Class '__main__.User' is not mapped 

我是 SQLalchemy 和 OOP 的新手,所以无法弄清楚我在这里做错了什么。任何帮助将不胜感激

请您参考如下方法:

问题源于在 User 上定义 __abstract__ == True。

来自docs :

__abstract__ causes declarative to skip the production of a table or mapper for the class entirely. A class can be added within a hierarchy in the same way as mixin (see Mixin and Custom Base Classes), allowing subclasses to extend just from the special class

如果你使 User 抽象,为了得到映射,它需要被另一个模型子类化,例如这有效:

class User(Base): 
    __tablename__ = 'User' 
    __abstract__ = True 
    id = Column('id', INTEGER(display_width=11), primary_key=True, nullable=False) 
    email = Column('email', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=100), unique=True) 
    password = Column('password', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=45)) 
    name = Column('name', VARCHAR(charset='utf8mb4', collation='utf8mb4_0900_ai_ci', length=100)) 
 
class AUser(User): 
    pass 
 
if __name__ == '__main__': 
    Base.metadata.create_all(bind=engine) 
 
    add_user = AUser(email = "testing@testing.com", 
                password = 'testing', 
                name = 'testing') 
    session.add(add_user) 
    session.commit()