简体   繁体   中英

Flask sqlAlchemy: Creating models for the existing database structure

我是 sqlAlchemy 的新手,我想知道是否有一种方法可以创建一个类,该类将映射到数据库中的现有表而不指定表的任何列(但所有列都可以作为对象的属性访问)?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM