查询sqlalchemy中的相关表

时间:2014-08-20 00:38:00

标签: python mysql sqlalchemy

所以我有两个表Employee和Details this。

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

1 个答案:

答案 0 :(得分:0)

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

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结果问题,我相信您的实际代码中有一些“额外”产生此错误......