【问题标题】:How do I write a query to get sqlalchemy objects from relationship?如何编写查询以从关系中获取 sqlalchemy 对象?
【发布时间】:2013-05-03 06:35:47
【问题描述】:

我正在学习 python 并使用以 sqlalchemy 作为 orm 的框架金字塔。我无法弄清楚关系是如何运作的。我有 2 张桌子、办公室和用户。外键在用户表“offices_id”上。我正在尝试进行查询,该查询将返回给我用户所属的办公室。

这就是我设置模型的方式。

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

【问题讨论】:

    标签: python sql sqlalchemy pyramid


    【解决方案1】:

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

    【讨论】:

    • stackoverflow 需要一个购买啤酒按钮。谢谢,工作得很好。
    • 现在我坚持做相反的事情。 DBSession.query(Office).join(User).all():office.user.name 不起作用。
    • 模型上的属性是name members,你试过office.members吗?这应该给你一个列表而不是单个对象,因为它是一对多的关系。
    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 2014-10-20
    • 2019-01-18
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多