Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This is from my blog post on pyNash
from sqlalchemy import create_engine
engine = create_engine('sqlite:///:memory:', echo=True)
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String, Float
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
balance = Column(Float)
group = Column(String)
def __init__(self, name, fullname, balance, group): = name
self.fullname = fullname
self.balance = balance = group
user1 = User('Bob', 'Big Bob', 1000000.00, 'Mob')
user2 = User('Linda', 'Linda Lu', 100.50, 'Diner')
user3 = User('Lil Bob', 'Bobby Jr', 100500.00, 'Mob')
user4 = User('Rachael', 'Rachael Rach', 125.50, 'Personal')
from sqlalchemy.orm import session maker
Session = sessionmaker(bind=engine)
db = Session()
for user in db.query(User).all():
print, user.balance
from sqlalchemy import func
from sqlalchemy.sql import label
label('members', func.count(,
label('total_balance', func.sum(User.balance))).group_by(
results = db.query(,
label('members', func.count(,
label('total_balance', func.sum(User.balance))).group_by(
for result in results:
print "%s has %i members with a balance of %d" % (, result.members, result.total_balance)

This comment has been minimized.

Copy link

commented Apr 11, 2018

line 21 : Base.metadata.create_all(engine)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.