我有要执行基于 ORM 的查询的表。
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
is_active = Column(Boolean, server_default="1", nullable=False)
is_deleted = Column(Boolean, server_default="0", nullable=False)
created_at = Column(DateTime, nullable = False, default=func.now())
first_name = Column(String(30), nullable=False)
surname_name = Column(String(30), nullable=False)
class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
is_active = Column(Boolean, server_default="1", nullable=False)
is_deleted = Column(Boolean, server_default="0", nullable=False)
created_at = Column(DateTime, nullable = False, default=func.now())
first_name = Column(String(30), nullable=False)
surname_name = Column(String(30), nullable=False)
appointments = relationship("ChildAppointment", backref="child")
class ParentChild(Base):
'''provides a many to many relationship for parent and child'''
__tablename__ = 'parent_child'
id = Column(Integer, primary_key=True)
is_active = Column(Boolean, nullable=False, server_default="1")
is_deleted = Column(Boolean, nullable=False, server_default="0")
parent_id = Column(Integer, ForeignKey('parent.id'), nullable=False)
child_id = Column(Integer, ForeignKey('child.id'))
parents = relationship("Parent", backref="parent_child")
children = relationship("Child", backref="parent_child")
class ChildAppointment(Base):
__tablename__ = 'child_appointment'
id = Column(Integer, primary_key=True)
is_active = Column(Boolean, nullable=False, server_default="1")
is_deleted = Column(Boolean, nullable=False, server_default="0")
created_at = Column(DateTime, nullable = False, default=func.now())
child_id = Column(Integer, ForeignKey('child.id'))
date_appointment = Column(DateTime, nullable = False)
我想查询表ParentChild
并通过 SQLAlchemy 关系魔术,我想获取孩子的最新约会日期,这意味着我需要date_appointment
在子表中排序的结果。
我在这里按照@zeek 的示例进行了操作,并提出了以下建议:
for data in session.query(ParentChild).join(Child.appointments).filter(ParentChild.parent_id == 1).\
order_by(Child.appointments.date_appointment.desc()).all():
但是,我得到了错误attributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object associated with Child.appointments has an attribute 'date_appointment'
我的场景打破了该链接中给出的内容,因为我有一张额外的桌子,因为我有 4 张桌子,所以我无法调整他的答案以适合我的。
谢谢。