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

1.3k views Asked by At

I don't get it. I'm trying to start a brand new table in MS SQL Server 2012 with the following:

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

NOTE: This is a BRAND NEW TABLE! There is no data in it at all

Next, this is the Database.py file:

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

It's also to note that I'm using SQLAlchemy 1.4.3, if that helps out.

and in the 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()

Now what I've googled on this "Class 'builtins.dict' is not mapped", most of the solutions brings me to marshmallow-sqlalchemy package which I've tried, but I'm still getting the same error. So I've tried moving the Base.metadata.create_all(engine) from the Database.py into the main.py. I also tried implementing a init function in the Inventory class, and also calling the Super().init, which doesn't work

So what's going on?? Why is it failing and is there a better solution to this problem?

1

There are 1 answers

2
AlwaysLearning On BEST ANSWER

Try creating Inventory objects:

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)
]