sqlalchemy关系映射

时间:2011-11-28 09:55:49

标签: python orm sqlalchemy

您好我有一个简单的问题 - 我有2个表(地址和用户 - 用户有一个地址,很多用户可以住在同一个地址)...我创建了一个sqlalchemy映射,如下所示: 当我得到我的会话并尝试查询类似

的内容时
    class Person(object):
'''
classdocs
'''
 idPerson = Column("idPerson", Integer, primary_key = True)
 name = Column("name", String)
 surname = Column("surname", String)
 idAddress = Column("idAddress", Integer, ForeignKey("pAddress.idAddress"))
 idState = Column("idState", Integer, ForeignKey("pState.idState"))
 Address = relationship(Address, primaryjoin=idAddress==Address.idAddress)

class Address(object):
'''
Class to represent table address object
'''
 idAddress = Column("idAddress", Integer, primary_key=True)
 street = Column("street", String)
 number = Column("number", Integer)
 postcode = Column("postcode", Integer)
 country = Column("country", String) 
 residents = relationship("Person",order_by="desc(Person.surname, Person.name)", primaryjoin="idAddress=Person.idPerson") 




    self.tablePerson = sqlalchemy.Table("pPerson", self.metadata, autoload=True)
    sqlalchemy.orm.mapper(Person, self.tablePerson)
    self.tableAddress = sqlalchemy.Table("pAddress", self.metadata, autoload=True)
    sqlalchemy.orm.mapper(Address, self.tableAddress) 


myaddress = session.query(Address).get(1);
print myaddress.residents[1].name

=>我得到TypeError:'RelationshipProperty'对象不支持索引

我知道居民可以在那里定义这种关系,但我怎样才能获得给定地址所分配的居民名单?! 感谢

2 个答案:

答案 0 :(得分:3)

您在错误的地方定义关系。我认为您将Declarative Extensionnon-declarative混合使用:

  1. 使用declarative时,您可以在model中定义关系。
  2. 否则,您在将model映射到table
  3. 时定义它们

    如果您正在执行选项-2,那么您需要从relationship中删除models个定义,并将其添加到映射器(只有一个):

    mapper(Address, tableAddress,
    properties={'residents': relationship(Person, order_by=(desc(Person.name), desc(Person.surname)), backref="Address"),}
    ) 
    

    关于上述代码的更多信息:

    1. 仅在一方定义关系。 backref关注另一方。
    2. 您不需要指定primaryjoin(只要您指定了ForeignKey,并且SA能够推断列)
    3. 您的order_by配置不正确,请参阅上面的代码了解适用的版本。

答案 1 :(得分:0)

您可以尝试在地址后定义Person,并使用backref to Address - 这将创建数组元素:

class Address(object):
 __tablename__ = 'address_table'
 idAddress = Column("idAddress", Integer, primary_key=True)

class Person(object):
 idPerson = Column("idPerson", Integer, primary_key = True)
 ...
 address_id = Column(Integer, ForeignKey('address_table.idAddress'))
 address = relationship(Address, backref='residents')

然后你可以查询:

myaddress = session.query(Address).get(1);
for residents in myaddress.residents:
  print name

此外,如果您在地址中有很多居民,您可以使用加入进一步过滤:

resultset = session.query(Address).join(Address.residents).filter(Person.name=='Joe')
# or
resultset = session.query(Person).filter(Person.name=='Joe').join(Person.address).filter(Address.state='NY')
and resultset.first() or resultset[0] or resultset.get(...) etc...