Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sqlalchemy reflected table to orm?

I reflected an existing sqlalchemy table using:

import sqlalchemy as sa
db_engine = sa.create_engine('postgres+psycopq2://postgres:pwrd@localhost/test')
meta = sa.MetaData()
records = sa.Table('records', meta, autoload=True, autoload_with=db_engine)

now when I try to add data into it via

from sqlalchemy.orm insert sessionmaker
Session = sessionmaker(bind=db_engine)
session = Session()

new_record = records(Col1='sdf', Col2='sdsfdadf')
session.add(new_record)
session.commit()

I get an error with

TypeError: 'Table' object is not callable

isn't a reflected table usable in the same way that a declared table is?

like image 850
KillerSnail Avatar asked Oct 13 '25 09:10

KillerSnail


1 Answers

You have to declare your own model class first, as Ilja Everilä suggested:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Records(Base):
    __table__ = sa.Table('records', meta, autoload=True, autoload_with=db_engine)

Then you may use the new model class Records to operate database:

new_record = Records(Col1='sdf', Col2='sdsfdadf')
session.add(new_record)
session.commit()
like image 113
YKL Avatar answered Oct 14 '25 23:10

YKL