views:

50

answers:

2

Using SQLAlchemy, given tables such as these:

locations_table = Table('locations', metadata,
    Column('id',        Integer, primary_key=True),
    Column('name', Text),
)

players_table = Table('players', metadata,
    Column('id',                 Integer, primary_key=True),
    Column('email',           Text),
    Column('password',   Text),
    Column('location_id',  ForeignKey('locations.id'))
)

and classes such as these:

class Location(object):
    def __init__(self, name):
        self.name = name

    def __repr__(self):
        return '<Location: %s, %s>' % (self.name)

mapper(Location, locations_table)

class Player(object):
    def __init__(self, email, password, location_id):
        self.email = email
        self.password = password
        self.location_id = location_id

    def __repr__(self):
        return '<Player: %s>' % self.email

mapper(Player, players_table)

and code like this:

location = session.query(Location).first()
player = session.query(Player).first()

(simplified).

How would I go about modifying that to support actions such as these:

# assign location to player using a Location object, as opposed to an ID
player.location = location
# access the Location object associated with the player directly
print player.location.name

and if SQLAlchemy permits:

# print all players having a certain location
print location.players

?

+1  A: 

Use sqlalchemy's relation feature:

http://www.sqlalchemy.org/docs/ormtutorial.html#building-a-relation

XUE Can
A: 

This should work for you:

mapper(Player, players_table, properties={'location'=relation(Location, uselist=False, backref=backref('players'))})

That way you can access the location directly as you won't get a list. Other than that, you can do location.players which will give you an InstrumentedList back, so you can iter over the players

Jokey