3

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)?

3

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I found this solution particularly idiotproof. A single look at pypi and I had the full database modeled out less than one minute later
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

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.