Skip to content

Instantly share code, notes, and snippets.

@Mgancita
Last active March 15, 2022 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Mgancita/5329bbbe3c1b470db424ec8608fed409 to your computer and use it in GitHub Desktop.
Save Mgancita/5329bbbe3c1b470db424ec8608fed409 to your computer and use it in GitHub Desktop.
from sqlalchemy import Column, create_engine, Integer, String
from sqlalchemy.orm import declarative_base, sessionmaker
# Create model
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
nickname = Column(String)
# Create tables
engine = create_engine('postgresql+psycopg2://scott:tiger@localhost/mydatabase')
Base.metadata.create_all(engine)
# Create session
Session = sessionmaker(bind=engine)
# Create user
ed_user = User(name='ed', fullname='Ed Jones', nickname='edsnickname')
session.add(ed_user)
# Read user
session.query(User).filter_by(name='ed').first()
# <User(name='ed', fullname='Ed Jones', nickname='edsnickname')>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment