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)?
-
Check out this: build-a-flask-application-around-an-already-existing-database3sky– 3sky2018-06-18 16:28:16 +00:00Commented Jun 18, 2018 at 16:28
-
1Have a look at the automap extension: docs.sqlalchemy.org/en/latest/orm/extensions/automap.htmlIlja Everilä– Ilja Everilä2018-06-18 16:38:26 +00:00Commented Jun 18, 2018 at 16:38
-
Also have you read stackoverflow.com/questions/17652937/…?Ilja Everilä– Ilja Everilä2018-06-18 16:55:20 +00:00Commented Jun 18, 2018 at 16:55
Add a comment
|
2 Answers
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.
1 Comment
abogaard
I found this solution particularly idiotproof. A single look at pypi and I had the full database modeled out less than one minute later
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
1 Comment
Ilja Everilä
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.