Created
March 1, 2013 13:38
-
-
Save jasonamyers/5064720 to your computer and use it in GitHub Desktop.
This is from my blog post on pynash.org on 2013-03-01
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from sqlalchemy import create_engine | |
engine = create_engine('sqlite:///:memory', echo=True) | |
from sqlalchemy.ext.declarative import declarative_base | |
from sqlalchemy.ext.hybrid import hybrid_property | |
Base = declarative_base() | |
from sqlalchemy import Column, Integer, String, Float | |
class Order(Base): | |
__tablename__ = 'orders' | |
order_id = Column(Integer, primary_key=True) | |
order_reference_code = Column(String) | |
merchandise_cost = Column(Float) | |
tax = Column(Float) | |
shipping = Column(Float) | |
def __init__(self, order_reference_code, merchandise_cost, tax, shipping): | |
self.order_reference_code = order_reference_code | |
self.merchandise_cost = merchandise_cost | |
self.tax = tax | |
self.shipping = shipping | |
@hybrid_property | |
def grand_total(self): | |
rollup_fields = [ | |
'merchandise_cost', | |
'tax', | |
'shipping', | |
] | |
total = sum([self.__getattribute__(x) for x in rollup_fields]) | |
return round(total, 2) | |
Base.metadata.create_all(engine) | |
order1 = Order('ABC', 57.50, 11.75, 6.00) | |
order2 = Order('BCD', 21.42, 4.72, 3.00) | |
order3 = Order('CDE', 1000.50, 80.34, 0.00) | |
order4 = Order('DEF', 500.50, 45.34, 100.00) | |
from sqlalchemy.orm import sessionmaker | |
Session = sessionmaker(bind=engine) | |
db = Session() | |
db.add(order1) | |
db.add(order1) | |
db.add(order1) | |
db.add(order1) | |
db.commit() | |
for order in db.query(Order).all(): | |
print order.order_reference_code, order.grand_total |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment