Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- from sqlalchemy import (
- Boolean, Column,
- ForeignKey, Integer,
- String, create_engine,
- )
- from sqlalchemy.ext.declarative import declarative_base
- from sqlalchemy.orm import backref, joinedload, relationship, sessionmaker
- engine = create_engine('sqlite:///:memory:', echo=True)
- Base = declarative_base()
- Session = sessionmaker(bind=engine)
- class Company(Base):
- __tablename__ = 'companies'
- id = Column(Integer, primary_key=True)
- name = Column(String)
- class User(Base):
- __tablename__ = 'users'
- id = Column(Integer, primary_key=True)
- name = Column(String)
- company_id = Column(Integer, ForeignKey(Company.id))
- is_active = Column(Boolean)
- company = relationship('Company', backref=backref('users', cascade='all'))
- if __name__ == '__main__':
- Base.metadata.create_all(engine)
- session = Session()
- acme = Company(name='ACME')
- bob = User(name='Bob', is_active=True, company=acme)
- alice = User(name='Alice', is_active=False, company=acme)
- session.add(bob)
- session.add(alice)
- session.flush()
- session.expire_all()
- company_with_active: Company = (
- session.query(Company)
- .join(User)
- .options(joinedload(Company.users))
- .filter(
- Company.name == 'ACME',
- User.is_active.is_(True),
- )
- .one()
- )
- print('\n'*3)
- print('Company with active users:')
- print('\n'*3)
- print(company_with_active.name)
- for user in company_with_active.users:
- user: User
- print(user.name)
Advertisement
Add Comment
Please, Sign In to add comment