繁体   English   中英

SQLalchemy中的多个联接

[英]Multiple join in SQLalchemy

我有一些看起来像下面的对象。 我有一些属性单元,其中包含一个或多个租户,并且租户对象与用户具有一对一关系

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'对象没有属性'User'”错误。

如何获得该用户的加入?

Tenant上没有User属性,因为您没有定义属性。 您在usr_users中将其称为usr_users,因此应以tenant.usr_users身份tenant.usr_users访问。

暂无
暂无

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

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