Slavskii Sergei
Slavskii Sergei

Reputation: 168

Flask sqlAlchemy: Creating models for the existing database structure

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

Answers (2)

faisal
faisal

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

mad_
mad_

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

Related Questions