【发布时间】:2015-04-11 23:11:24
【问题描述】:
从 SQLAlchemy 文档中的many-to-many relationship example 开始,我想添加一个属性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 数据库一起使用。
【问题讨论】:
-
但是使用
children.first()有什么问题? -
@IgorHatarist 你试过吗?
'RelationshipProperty' object has no attribute 'first'失败 -
尝试
children[0]获取第一个孩子。但这并不能完全回答你的问题。请问您为什么需要跟踪第一个和最后一个孩子?孩子的排序是如何进行的? -
@BrechtMachiels 对不起,当然是
children[0]。 -
@van 是的,
children[0]仅适用于实例。就我而言,孩子是具有开始/结束时间的事件。我想在父级上创建start_time和end_time属性,分别从第一个和最后一个子级获取值。
标签: python mysql orm sqlalchemy