sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.dict' is not mapped AND using marshmallow-sqlalchemy

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'builtins.dict' is not mapped AND using marshmallow-sqlalchemy

我不明白。我正在尝试在 MS SQL Server 2012 中启动一个全新的 table,内容如下:

In SQL Server:
TABLE [dbo].[Inventory](
[Index_No] [bigint] IDENTITY(1,1) NOT NULL,
[Part_No] [varchar(150)] NOT NULL,
[Shelf] [int] NOT NULL,
[Bin] [int] NOT NULL,
PRIMARY KEY CLUSTERED 
(
    [Index_No] ASC
)
UNIQUE NONCLUSTERED 
(
    [Part_No] ASC
)
GO

注意:这是全新的 TABLE!里面根本没有数据

接下来,这是 Database.py 文件:

import pymssql
from sqlalchemy import create_engine, Table, MetaData, select, Column, Integer, Float, String, text, 
func, desc, and_, or_, Date, insert

from marshmallow_sqlalchemy import SQLAlchemyAutoSchema

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

USERNAME = "name"
PSSWD = "none_of_your_business"
SERVERNAME = "MYSERVER"
INSTANCENAME = "\SQLSERVER2012"
DB = "Inventory"

engine = create_engine(f"mssql+pymssql://{USERNAME}:{PSSWD}@{SERVERNAME}{INSTANCENAME}/{DB}")

class Inventory(Base):

    __tablename__ = "Inventory"

    Index_No = Column('Index_No', Integer, primary_key=True, autoincrement=True)
    Part_No = Column("Part_No", String, unique=True)
    Shelf = Column("Shelf", Integer)
    Bin = Column("Bin", Integer)

    def __repr__(self):
        return f'Drawing(Index_No={self.Index_No!r},Part_No={self.Part_No!r}, Shelf={self.Shelf!r}, ' \ 
                         f'Bin={self.Bin!r})'


class InventorySchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Inventory
        load_instance = True

还要注意,我使用的是 SQLAlchemy 1.4.3,如果有帮助的话。

并在 main.py

import Database as db

db.Base.metadata.create_all(db.engine)

data_list = [{Part_No:123A, Shelf:1, Bin:5},
             {Part_No:456B, Shelf:1, Bin:7},
             {Part_No:789C, Shelf:2, Bin:1}]


with db.Session(db.engine, future=True) as session:
    try:
        session.add_all(data_list) #<--- FAILS HERE AND THROWS AN EXCEPTION
        session.commit()

    except Exception as e:
        session.rollback()
        print(f"Error! {e!r}")
        raise

    finally:
        session.close()

现在我在谷歌上搜索了这个“Class 'builtins.dict' 未映射”,大多数解决方案都将我带到了我尝试过的 marshmallow-sqlalchemy 包,但我仍然遇到同样的错误。所以我尝试将 Base.metadata.create_all(引擎)从 Database.py 移动到 main.py。我还尝试在 Inventory class 中实现 init 函数,并调用 Super().init,但没有工作

所以这是怎么回事??为什么会失败,是否有更好的解决方案?

尝试创建清单对象:

data_list = [
  Inventory(Part_No='123A', Shelf=1, Bin=5),
  Inventory(Part_No='456B', Shelf=1, Bin=7),
  Inventory(Part_No='789C', Shelf=2, Bin=1)
]