2010-02-07 97 views
1

使用SQLAlchemy的,給定的表,如這些:如何使用SQLAlchemy在表之間建立關係?

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')) 
) 

和類如這些:

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) 

和這樣的代碼:

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

(簡化的)。

我怎麼會去修改,以支持行動,像這樣的:

# 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 

如果SQLAlchemy的許可:

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

回答

1

這應該爲你工作:

映射器(播放器,players_table,性能= { '位置'=關係(位置,uselist =假backref = backref('players'))})

這樣你就可以直接訪問該位置,因爲你不會得到一個列表。除此之外,你可以做location.players,它會給你一個InstrumentedList,所以你可以通過球員

相關問題