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

标签 python sqlalchemy

我正在为 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()

关于python - 如何解决 sqlalchemy.orm.exc.UnmappedInstanceError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51589930/

相关文章:

python - 从实例列表中创建一个简单列表的 pythonic 习惯用法是什么?

python - 使用PIL将一张512*256的图片分成2张每张256*256的图片

python - 在循环中使用不同的名称保存数组

python - 如何将 Keras 与网络摄像头一起使用?

python - 使用 WHERE 在 SQLAlchemy Core 中进行批量更新

python - SQLAlchemy 声明性语法中具有抽象基的多态多对多关系

python - 求三个数的最高乘积

python - 在 Elasticsearch 中搜索句点和连字符分隔的字段

python - 通过 alembic 脚本并发数据库表索引

flask - Flask-Admin 中的自定义和可排序列