Frage

Verwenden von SQLALCHEMY, angegebene Tabellen wie folgt:

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

und Klassen wie diese:

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)

und Code wie diesen:

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

(vereinfacht).

Wie würde ich das ändern, um dies zu ändern, um Aktionen wie diese zu unterstützen:

# 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

und wenn sqlalchemy zulässt:

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

?

War es hilfreich?

Lösung

Dies sollte für Sie funktionieren:

Mapper (Player, Player_table, Properties = {'Ort' = Beziehung (Ort, Uselist = False, BackRef = BackRef ('Spieler'))})

Auf diese Weise können Sie direkt auf den Standort zugreifen, da Sie keine Liste erhalten. Abgesehen davon können Sie Lokalplayer machen, die Ihnen eine instrumentierte Liste zurückgeben

Andere Tipps

Verwenden Sie die Beziehungsfunktion von Sqlalchemy:

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top