Код: Выделить всё
#Players Table for the database
class Players(masdb.Model):
__tablename__ = 'players'
id=masdb.Column(masdb.Integer, primary_key=True)
game_key=masdb.Column(masdb.String(255))
games=masdb.relationship('Game', backref='player', lazy=True)
def __init__(self, game_key): # constructor function
self.game_key = game_key
#Game table for the database
class Game(masdb.Model):
__tablename__ = 'game'
id = masdb.Column(masdb.Integer, primary_key=True)
settlement_name = masdb.Column(masdb.String(50))
created_at = masdb.Column(masdb.DateTime, default=datetime.datetime.now)
player_id = masdb.Column(masdb.Integer, ForeignKey('players.id'))
def __init__(self, settlement_name, player_id):
self.settlement_name = settlement_name
self.player_id = player_id
Код: Выделить всё
class PlayersSchema(ma.Schema):
class Meta:
fields = ('id', 'game_key')
class GameSchema(ma.Schema):
class Meta:
fields = ('id', 'settlement_name', 'created_at', 'player_id')
# Classes for serializing data
player_schema = PlayersSchema()
players_schema = PlayersSchema(many=True)
game_schema = GameSchema()
games_schema = GameSchema(many=True)
Код: Выделить всё
@app.route('/getGamesByGameKey//', methods =['GET'])
def getGamesByGameKey(cookieGame_Key):
findPlayerStatement = select(Players).filter_by(game_key = cookieGame_Key) # SQL statement
playerObject = masdb.session.execute(findPlayerStatement).first() # Executes the statement. I think first() just stops the search at the first find always returning an array of 1.
findGamesStatement = select(Game).filter_by(player_id = playerObject[0].id) #Data will only ever have a single entry due to the above, hence the playerObject[0]
games = masdb.session.execute(findGamesStatement).all()
results = games_schema.dump(games)
return jsonify(results)
Я создал 3 игры в моей базе данных для моего теста и связал их всех с одним игроком для моего теста. Когда я отправляю им запрос, я получаю следующий ответ:
Код: Выделить всё
[
{},
{},
{}
]
Код: Выделить всё
games = masdb.session.execute(findGamesStatement).all()Строка
Если я изменю .all() на .first() он вернет только один объект, и даже при использовании games_schema (у которого много = True) это будет работать! Он просто... возвращает только один элемент. Так что в самой схеме, похоже, нет ничего плохого. Результат следующий:
Код: Выделить всё
[
{
"created_at": "2023-04-10T20:23:39",
"id": 120,
"player_id": 118,
"settlement_name": "Multi Game to Get"
}
]
Подробнее здесь: https://stackoverflow.com/questions/759 ... n-empty-li