简体   繁体   English

在sqlalchemy中查询相关表

[英]Querying related tables in sqlalchemy

So I have two tables Employee and Details like this. 所以我有两个这样的表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))
    ............

Now what I want to do is get all the employees and their corresponding details, here is what I tried. 现在我要做的是获取所有员工及其相应的详细信息,这就是我尝试过的。

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

The problem with this is that it prints everything twice. 问题是它会将所有内容打印两次。 I tried using .join() and also prints the results twice. 我尝试使用.join(),并且还会打印两次结果。

What I want to achieve is like 我想要实现的就像

print Employee.name
print Employee.details.email

If you really care only about few columns, you can specify them in the query directly: 如果您只关心几列,则可以直接在查询中指定它们:

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

If you do really want to load object instances, then I would do it differently: 如果您确实要加载对象实例,那么我会做不同的事情:

# 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)

As to your duplicate result problem, I believe you have some "extra" in your real code which produces this error... 至于duplicate结果问题,我相信您的真实代码中有一些“多余”的东西会产生此错误...

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

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