Skip to content

Instantly share code, notes, and snippets.

@csabatini
Created December 4, 2017 03:29
Show Gist options
  • Save csabatini/31b4f3758730ed7286efc6142e37becb to your computer and use it in GitHub Desktop.
Save csabatini/31b4f3758730ed7286efc6142e37becb to your computer and use it in GitHub Desktop.
Auto-create models from an existing db with SQLAlchemy
from __future__ import print_function
from sqlalchemy import *
from sqlalchemy.orm import create_session
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = \
create_engine("postgresql://...")
metadata = MetaData(bind=engine)
class Team(Base):
__table__ = Table('team', metadata, autoload=True)
class Player(Base):
__table__ = Table('player', metadata, autoload=True)
class Game(Base):
__table__ = Table('game', metadata, autoload=True)
class PlayPlayer(Base):
__table__ = Table('play_player', metadata, autoload=True)
session = create_session(bind=engine)
print(dir(session.query(PlayPlayer).first()))
team = session.query(Team).first()
debugstring = "team_id: {0} - name: {1} - city: {2}".format(
team.team_id, team.name, team.city)
# print(debugstring)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment