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?
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With