Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Sqlalchemy Define class from existing table

import sqlalchemy as sa

psw = "verysecret"
db = "accounts"

# create an engine
pengine = sa.create_engine('postgresql+psycopg2://postgres:' + psw +'@localhost/' + db)

from sqlalchemy.ext.declarative import declarative_base
# define declarative base
Base = declarative_base()

# reflect current database engine to metadata
metadata = sa.MetaData(pengine)
metadata.reflect()

# build your User class on existing `users` table
class User(Base):
    __table__ = sa.Table("users", metadata)
    
# call the session maker factory
Session = sa.orm.sessionmaker(pengine)
session = Session()

# filter a record 
session.query(User).filter(User.id==1).first()
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #Sqlalchemy #Define #class #existing #table
ADD COMMENT
Topic
Name
7+7 =