Skip to content

Instantly share code, notes, and snippets.

@pawl
Created March 9, 2017 07:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save pawl/2393a4c3bfc98f73a09f63c298f305d7 to your computer and use it in GitHub Desktop.
testing in_ loading strategy from: http://stackoverflow.com/a/39073859
from sqlalchemy import create_engine, Column, ForeignKey, Integer, TEXT
from sqlalchemy.orm import relationship, scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql://root@localhost/test?charset=utf8mb4',
convert_unicode=True,
echo=True)
session = scoped_session(sessionmaker(autocommit=False,
autoflush=False,
bind=engine))
Base = declarative_base()
Base.query = session.query_property()
class Post(Base):
__tablename__ = 'posts'
id = Column(Integer, primary_key=True)
products = relationship('Product')
class Product(Base):
__tablename__ = 'products'
id = Column(Integer, primary_key=True)
post_id = Column(Integer, ForeignKey('posts.id'), index=True)
links = relationship('ProductLink')
class ProductLink(Base):
__tablename__ = 'links'
id = Column(Integer, primary_key=True)
product_id = Column(Integer, ForeignKey('products.id'), index=True)
link = Column(TEXT)
#Base.metadata.drop_all(engine)
Base.metadata.create_all(engine)
# create new rows if database is empty
first_result = Post.query.first()
if not first_result:
for x in range(50):
products = [
Product(links=[ProductLink() for z in range(9)])
for y in range(12)
]
session.add(Post(products=products))
session.commit()
posts = Post.query.limit(20)
post_ids = {post.id for post in posts}
session.query(Product).filter(Product.post_id.in_(post_ids)).all()
for post in posts:
for product in post.products:
print product.id
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment