Grzegorz Biziel
Jan Słowik
wroc.py #17, 7 lipca 2015
user_table = Table('USER', Metadata
Column('id', Integer, primary_key=True, nullable=False),
Column('name', String(length=64), nullable=False))
class User(Base):
__table__ = user_table
name = user_table.c.name
user_table = Table('USER', Metadata,
Column('id', Integer, primary_key=True, nullable=False),
Column('name', String(length=64), nullable=False))
class User(Base):
def __init__(self, name:
self.name = name
mapper(User, user_table)
class User(Base):
__table__ = user_table
tasks = relationship('Task', backref='user')
class Task(Base):
...
mapper(User, user_table, properties={
'tasks' : relationship(Task, backref='user')
})
session
.query(Klasa_pobieranego_obiektu)
.join(Inna_klasa)
.filter(Inna_klasa.atrybut == wartosc)
.all()
ORM może być rozpatrywany jako anty-wzorzec
base_product_table = [...]
specialization_table = [...]
product_join = join(
base_product_table,
specialization_table)
class Product(Base):
__table__ = product_join
[...]
class Order(Base):
__table__ = order_table
id = order_table.c.id
state = order_table.c.state
[...]
__mapper_args__ = {
'polymorphic_on': state
}
class InProgressOrder(Order):
[...]
__mapper_args__ = {
'polymorphic_identity': 'INPROGRESS',
}
[task for task in user.tasks
if task.project.code == project_code ]
Domyślnie z powodu na lazy loading wykonanie tego fragmentu wiązałoby się z wieloma zapytaniami do bazy danych.
session.query(User)
.options(
joinedload(User.tasks)
.joinedload(Task.project))
.filter([...]).first()
session.query(User)
.options(
subquery(User.tasks)
.joinedload(Task.project))
.filter([...]).first()
Wczesne ładowanie na podstawie danych dostępnych w wyniku zapytaniu.
user = session.query(User)
.join(User.tasks)
.options(contains_eager(User.tasks))
.filter(User.id == user_id,
Task.state == state)
.first()
from sqlalchemy.orm import aliased
adalias1 = aliased(Address)
adalias2 = aliased(Address)
session.query(User).\
join(adalias1, User.addresses).\
join(adalias2, User.addresses).\
filter(adalias1.email_address=='jack@google.com').\
filter(adalias2.email_address=='j25@yahoo.com')
Przenoszenie atrybutów między obiektami będącymi w relacji
class Project(Base):
[...]
codename = project_table.c.codename
task = relationship('Task', backref='project')
class Task(Base):
[...]
project_codename
= association_proxy('project', 'codename')