从many-to-many relationship example开始根据 SQLAlchemy 文档,我想添加一个属性 first_child
,它将返回由关系定义的 children
的第一个子级。 first_child
属性需要可在 association_proxy
中使用属性定义,例如下面的 first_child_id
。
from sqlalchemy import Table, Column, Integer, ForeignKey
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
Base = declarative_base()
association_table = Table('association', Base.metadata,
Column('left_id', Integer, ForeignKey('left.id')),
Column('right_id', Integer, ForeignKey('right.id'))
)
class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship("Child", secondary=association_table)
first_child = ???
first_child_id = association_proxy('first_child', 'id')
class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
我想我需要将 first_child
声明为 hybrid_property
or a column_property
,但我不知道如何返回第一个元素。
除了 first_child
之外,我还需要 last_child
和关联的 last_child_id
属性。
我正在将 SQLAlchemy 与 MySQL 数据库结合使用。
最佳答案
如果您需要的是最小开始时间和最大结束时间,那么我将仅对这些列使用column_property
:
association_table = Table(
'association', Base.metadata,
Column('left_id', Integer, ForeignKey('left.id')),
Column('right_id', Integer, ForeignKey('right.id'))
)
class Child(Base):
__tablename__ = 'right'
id = Column(Integer, primary_key=True)
start_time = Column(DateTime)
end_time = Column(DateTime)
class Parent(Base):
__tablename__ = 'left'
id = Column(Integer, primary_key=True)
children = relationship(
"Child",
secondary=association_table,
backref="parents",
)
min_start_time = column_property(
select([Child.start_time.label("min_start_time")])
.where(Child.id == association_table.c.right_id)
.where(id == association_table.c.left_id)
.order_by(Child.start_time.asc())
.limit(1)
)
max_end_time = column_property(
select([Child.end_time.label("max_end_time")])
.where(Child.id == association_table.c.right_id)
.where(id == association_table.c.left_id)
.order_by(Child.end_time.desc())
.limit(1)
.as_scalar()
)
但是,如果您需要关系中的多个此类特殊列,那么使用 hybrid_property
可能会更有效。
关于python - SQLAlchemy ORM : proxy attribute pointing to the first element of a relation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28456760/