Skip to content

Instantly share code, notes, and snippets.

@roganjoshp
Created August 21, 2019 20:15
Show Gist options
  • Save roganjoshp/7e1075d83c0f03fdbc5ffb9bd234ced9 to your computer and use it in GitHub Desktop.
Save roganjoshp/7e1075d83c0f03fdbc5ffb9bd234ced9 to your computer and use it in GitHub Desktop.
How to join without loop
from sqlalchemy import (create_engine, and_, Column, Integer, String,
ForeignKey, Float)
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import random
import pandas as pd
engine = create_engine('sqlite:///:memory:')
Base = declarative_base()
class Product(Base):
__tablename__ = 'product'
id = Column(Integer, primary_key=True)
product_code = Column(Integer, index=True)
name = Column(String(50))
something = Column(String(50))
class Forecast(Base):
__tablename__ = 'forecast'
id = Column(Integer, primary_key=True)
product_id =Column(Integer, ForeignKey('product.id'),
index=True)
week_number = Column(Integer)
forecast_qty = Column(Float)
product = relationship(Product)
if __name__ == '__main__':
Session = sessionmaker(bind=engine)
session = Session()
Base.metadata.create_all(engine)
# Create a fake product
prod = Product(product_code=1234,
name='Stag do in Vegas',
something="No, I'm not that guy")
session.add(prod)
session.commit()
# Create fake forecast for the next 4 weeks
for x in range(4):
demand = random.randint(0, 100)
forecast = Forecast(product_id=prod.id,
week_number=x,
forecast_qty=demand)
session.add(forecast)
session.commit()
# NOW QUERY
forecast = session.query(Forecast).join(Product).all()
expanded = []
for item in forecast: # <-- I want rid of this loop
item_dict = item.__dict__
product_name = item.product.name
item_dict['product_name'] = product_name
expanded.append(item_dict)
df = pd.DataFrame(expanded)
print(df.head())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment