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 に答える