1

使用 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

?

4

2 回答 2

3

使用 sqlalchemy 的关系功能:

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

于 2010-02-07T13:44:13.317 回答
1

这应该适合你:

映射器(播放器,players_table,属性={'location'=relation(位置,uselist=False,backref=backref('players'))})

这样您就可以直接访问该位置,因为您不会获得列表。除此之外,您可以执行 location.players 这将为您返回 InstrumentedList,因此您可以遍历播放器

于 2010-02-07T14:59:16.763 回答