Skip to content

Instantly share code, notes, and snippets.

@podhmo
Last active August 29, 2015 13:56
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 podhmo/9274178 to your computer and use it in GitHub Desktop.
Save podhmo/9274178 to your computer and use it in GitHub Desktop.
# -*- coding:utf-8 -*-
import sqlalchemy as sa
from sqlalchemy.sql import func as f
import sqlalchemy.orm as orm
from sqlalchemy.ext.declarative import declarative_base
Session = orm.scoped_session(orm.sessionmaker())
Base = declarative_base()
class Person(Base):
__tablename__ = "Person"
query = Session.query_property()
id = sa.Column(sa.Integer, primary_key=True)
blood = sa.Column(sa.String(1)) #sloppy
gender = sa.Column(sa.String(1)) #sloppy
"""
Person
id, gender, blood
1, F A
2, M AB
3, M B
4, F O
5, M O
"""
engine = sa.create_engine("sqlite://")
Session.bind = engine
Base.metadata.bind = engine
Base.metadata.create_all()
Session.add(Person(gender="F", blood="A"))
Session.add(Person(gender="M", blood="AB"))
Session.add(Person(gender="M", blood="B"))
Session.add(Person(gender="F", blood="O"))
Session.add(Person(gender="M", blood="O"))
q = Person.query
## q = some_filter(q)
q = q.with_entities(
Person.blood,
f.sum(sa.case([(Person.gender=="F", 1)], else_=0)).label("F"),
f.sum(sa.case([(Person.gender=="M", 1)], else_=0)).label("M"),
)
print("Blod, F, M")
for row in q.group_by(Person.blood).all():
print("{o.blood}, {o.F}, {o.M}".format(o=row))
"""
Blod, F, M
A, 1, 0
AB, 0, 1
B, 0, 1
O, 1, 1
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment