【发布时间】: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