Reputation: 3591
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?
Upvotes: 4
Views: 2416
Reputation: 542
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()
Upvotes: 4