【问题标题】:Multiple join in SQLalchemySQLalchemy 中的多重连接
【发布时间】:2015-01-06 07:45:44
【问题描述】:

我有一些如下所示的对象。我有一些属性单元,其中包含一个或多个租户,并且租户对象与用户是一对一的关系

class User(Base):
    """
    Application's user model.
    """
    __tablename__ = 'usr_users'
    usr_user_id = Column(Integer, primary_key=True)
    usr_email = Column(Unicode(50))
    _usr_password = Column('password', Unicode(64))
    usr_groups = Column(Unicode(256))
    usr_activated = Column(Boolean)

    tenant = relationship("Tenant", uselist=False, backref="usr_users")
class Tenant(Base):
    __tablename__ = 'ten_tenants'
    ten_tenant_id = Column(Integer, primary_key=True)
    ten_ptu_property_unit_id = Column(Integer, ForeignKey('ptu_property_units.ptu_property_unit_id'))
    ten_usr_user_id = Column(Integer, ForeignKey('usr_users.usr_user_id'))

class PropertyUnit(Base):
    __tablename__ = 'ptu_property_units'
    ptu_property_unit_id = Column(Integer, primary_key=True)
    ptu_pty_property_id = Column(Integer, ForeignKey('pty_propertys.pty_property_id'))

    tenants = relationship("Tenant")

我正在尝试提取属性的所有单元,包括租户信息和用户表中的电子邮件。

我设法很容易地获得了一个加入:

rows = DBSession.query(PropertyUnit).join(Tenant).filter(PropertyUnit.ptu_pty_property_id==request.GET['property_id']).order_by(PropertyUnit.ptu_number)
    units = rows.all()

我在模板中显示如下:

% for unit in units:
      <%
          tenants = unit.tenants
      %>
        <tr>
        <td><a href="/manager/unit?property_unit_id=${unit.ptu_number}">${unit.ptu_number}</a></td>
        <td>
        % for tenant in tenants:
            ${tenant.ten_usr_user_id},
        % endfor
        </td>
        </tr>
      % endfor

到目前为止一切顺利。现在我需要从租户外键中提取用户信息,所以我想我可以再添加一个连接:

rows = DBSession.query(PropertyUnit).join(Tenant).join(User).filter(PropertyUnit.ptu_pty_property_id==request.GET['property_id']).order_by(PropertyUnit.ptu_number)
    units = rows.all()

这似乎在 SQL 日志中有效,因为它生成了正确的 SQL,但我无法以与第一次相同的方式获取数据。这失败了:

% for unit in units:
      <%
          tenants = unit.tenants
      %>
        <tr>
        <td><a href="/manager/unit?property_unit_id=${unit.ptu_number}">${unit.ptu_number}</a></td>
        <td>
        % for tenant in tenants:
            <%
                user = tenant.User
            %>
            ${tenant.ten_usr_user_id},
        % endfor
        </td>
        </tr>
      % endfor

所以,上面的代码会抛出“'Tenant' object has no attribute 'User'”错误。

我如何获得该用户的加入?

【问题讨论】:

    标签: python sqlalchemy mako


    【解决方案1】:

    Tenant 上没有属性 User,因为您没有定义一个。您在 backref 中将其称为 usr_users,因此您应该以 tenant.usr_users 访问它。

    【讨论】:

      猜你喜欢
      • 2017-07-16
      • 1970-01-01
      • 2019-02-19
      • 2020-01-24
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 2021-04-03
      • 2013-12-05
      相关资源
      最近更新 更多