2013-05-08 85 views
1

我正在学习python,并使用框架金字塔和sqlalchemy作为orm。我无法弄清楚关系是如何工作的。我有2个桌子,办公室和用户。外键在用户表'offices_id'上。我试图做一个查询,将返回给我一个用户是什么办公室的一部分。如何编写查询以获取关系中的sqlalchemy对象?

这是我如何设置我的模型。

DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) 
Base = declarative_base() 

class User(Base): 
    __tablename__ = 'users' 
    id = Column(Integer, primary_key=True) 
    name = Column(Unicode(255), unique=True, nullable=False) 
    trec_number = Column(Unicode(255), unique=True, nullable=False) 
    office_id = Column(Integer, ForeignKey('offices.id')) 

class Office(Base): 
    __tablename__ = 'offices' 
    id = Column(Integer, primary_key=True) 
    name = Column(Unicode(255), unique=True, nullable=False) 
    address = Column(Unicode(255), unique=True, nullable=False) 
    members = relationship("User", backref='offices') 

在我看来,我怎么会写的查询将返回办公室信息给定用户?

我想这一点:

for user in DBSession.query(User).join(Office).all(): 
    print user.address 

,但我想我误解了查询的工作,因为我不断收到错误

AttributeError: 'User' object has no attribute 'address' 

当我这样做:

for user in DBSession.query(User).join(Office).all(): 
    print user.name 

它打印出用户名称很好,因为name是User类的一个属性。

我也无法得到逆工作

for offices in DBSession.query(Office).join(User).all(): 
    print offices.users.name 

回答

3

您需要使用您在backref参数用于访问Office模型的名称。尝试user.offices.address

+3

stackoverflow需要买一个啤酒按钮。谢谢,工作完美。 – 2013-05-08 22:49:50

+0

现在我被困在做反面。 DBSession.query(Office).join(User).all(): offices.user.name不起作用。 – 2013-05-09 14:40:23

+0

模型上的属性是名称成员,你有没有试过offices.members?这应该给你一个列表而不是单个对象,因为它是一对多的关系。 – 2013-05-09 14:44:43

相关问题