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)?
Asked
Active
Viewed 4,239 times
2
-
Check out this: [build-a-flask-application-around-an-already-existing-database](https://stackoverflow.com/questions/17652937/how-to-build-a-flask-application-around-an-already-existing-database) – 3sky Jun 18 '18 at 16:28
-
1Have a look at the automap extension: http://docs.sqlalchemy.org/en/latest/orm/extensions/automap.html – Ilja Everilä Jun 18 '18 at 16:38
-
Also have you read https://stackoverflow.com/questions/17652937/how-to-build-a-flask-application-around-an-already-existing-database? – Ilja Everilä Jun 18 '18 at 16:55
2 Answers
2
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.

faisal
- 79
- 6
-
I found this solution particularly idiotproof. A single look at pypi and I had the full database modeled out less than one minute later – abogaard Aug 19 '21 at 13:27
0
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

mad_
- 8,121
- 2
- 25
- 40
-
Declarative is usually preferred over classical mapping these days, though there's nothing wrong with the latter. Just that it might look a bit odd to many who then read various other tutorials etc. – Ilja Everilä Jun 18 '18 at 16:39