Reputation: 168
I am new to sqlAlchemy and I wonder if there is a way create a class that would be mapped to the existing table in DB without specifying any columns of the table (but all columns could be accessed as attributes of the object)?
Upvotes: 3
Views: 4683
Reputation: 99
This is how I generated models for flask-sqlalchemy which use MS SQL.
flask-sqlacodegen --flask mssql+pymssql://<username>:<password>@<server>/<database> --tables <table_names>> db_name.py
you have to install flask-sqlacodegen and pymssql though.
Upvotes: 3
Reputation: 8273
Have recently came across this issue. Try steps below:
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.orm import mapper, sessionmaker
class User(object): # class which can can act as ORM class
pass
dbPath = 'places.sqlite'
engine = create_engine('sqlite:///%s' % dbPath, echo=True) # create engine
metadata = MetaData(engine)
user_table= Table('user_existing_class', metadata, autoload=True) # create a Table object
mapper(User, user_table) # map Table to ORM class
Session = sessionmaker(bind=engine)
session = Session()
res = session.query(User).all()
res[1].name
Upvotes: 0