繁体   English   中英

在sqlalchemy中查询相关表

[英]Querying related tables in sqlalchemy

所以我有两个这样的表Employee和Details。

class Employee(Base):
    __tablename__ = 'employees'
    id = Column(Integer, Sequence('employee_id_seq'), primary_key=True)
    name = Column(String(50), nullable=False)
    ............

class Detail(Base):
    __tablename__ = 'details'
    id = Column(Integer, Sequence('detail_id_seq'), primary_key=True)
    start_date = Column(String(50), nullable=False)
    email = Column(String(50))
    employee_id = Column(Integer, ForeignKey('employee.id'))
    employee = relationship("Employee", backref=backref('details', order_by=id))
    ............

现在我要做的是获取所有员工及其相应的详细信息,这就是我尝试过的。

for e, d in session.query(Employee, Detail).filter(Employee.id = Detail.employee_id).all():
    print e.name, d.email

问题是它会将所有内容打印两次。 我尝试使用.join(),并且还会打印两次结果。

我想要实现的就像

print Employee.name
print Employee.details.email

如果您只关心几列,则可以直接在查询中指定它们:

q = session.query(Employee.name, Detail.email).filter(Employee.id == Detail.employee_id).all()
for e, d in q:
    print e, d

如果您确实要加载对象实例,那么我会做不同的事情:

# query all employees
q = (session.query(Employee)
        # load Details in the same query
        .outerjoin(Employee.details)
        # let SA know that the relationship "Employee.details" is already loaded in this query so that when we access it, SA will not do another query in the database
        .options(contains_eager(Employee.details))
        ).all()

# navigate the results simply as defined in the relationship configuration
for e in q:
    print(e)
    for d in e.details:
        print(" ->", d)

至于duplicate结果问题,我相信您的真实代码中有一些“多余”的东西会产生此错误...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM