I'm having trouble figuring out how to access the data on the 'one' side of a
'many-to-one' relationship.

If I have the following setup:

personTable = Table('person',
    Column('person_id', Integer),
    Column('name', String(20)),
    Column('address', ForeignKey('address.address_id'),
)

addressTable = Table('address',
    Column('address_id', Integer),
    Column('street', String(20),
)

class Person(object):
    pass

class Address(object):
    pass

personMapper = mapper(Person, personTable)

addressMapper = mapper(Address, addressTable,
    properties=dict(persons=relation(Person)))

Then I can do this:

session = create_session()

# Create one address
a = Address()
session.save(a)
a.street = "12 Maple Dr." 

# Create two persons, each having the same address.
p1 = Person()
p2 = Person()
session.save(p1)
session.save(p2)
p1.name = "Joe Smith"
p1.address = a.address_id
p2.name = "Jane Smith"
p2.address = a.address_id
session.flush()

OK, now if I get a person:

p = session.query(Person).select(Person.c.name=="Jane Smith")[0]

I expect to be able to do something like:

street = p.address.street

But this just complains about 'None' not having an attribute 'street'.

I'm confused by this, because if I wanted to look up addresses and get the
persons living there, I'm able to do something like:

a = sesion.query(Address).select(Address.c.address_id==1)[0]
name = a.persons[0].name

This will lazily-evaluate the relationship, and get the appropriate Person
record for me.

Why is it easy to go in one direction, but not in the other.  What am I missing?

Thanks.


-------------------------------------------------------------------------
Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo
http://sel.as-us.falkag.net/sel?cmd=lnk&kid=120709&bid=263057&dat=121642
_______________________________________________
Sqlalchemy-users mailing list
Sqlalchemy-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/sqlalchemy-users

Reply via email to