如何使用SQLAlchemy在表之间建立关系?
问题描述:
使用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
?
答
这应该为你工作:
映射器(播放器,players_table,性能= { '位置'=关系(位置,uselist =假backref = backref('players'))})
这样你就可以直接访问该位置,因为你不会得到一个列表。除此之外,你可以做location.players,它会给你一个InstrumentedList,所以你可以通过球员