Firebase循环通过值为Child的Child的Child

时间:2019-03-05 06:33:59

标签: python firebase loops

在名册中有一个团队ID列表。我试图将team_id循环到具有其他属性的子级中,并找到所有1岁以下的子级。

我已经找到了如何访问team_id的方法,但是我无法弄清楚如何遍历每个成员并计算有多少人符合要求。

roster_info_snapshot = cfm.child('rosters').child(team_id).get()

这是我目前正在使用的代码,用于返回团队中受伤球员的数量。

 # Number of injured players
elif data['name'] != 'John Madden' and '/injuries' in data['text'].lower():
    print('Injuries keyword found')
    msg = data['text'].lower().split()
    func_index = msg.index('/injuries')
    if(len(msg) > func_index + 1):
        try:
            print(f'Retrieving injuries info for {msg[func_index + 1]}')
            team_map_snapshot = cfm.child('teamMap').get()
            team_id = team_map_snapshot[msg[func_index + 1].lower()]
            team_info_snapshot = cfm.child('teams').child(team_id).get()

            msg = f"{data['name']}, you sent '{data['text']}'"
            send_message(f"{team_info_snapshot['displayName']} have {team_info_snapshot['ovrRating']} players injured")

        except Exception as e:
            print(e)
            send_message('Sorry, an error occurred processing your request.')

    else:
        send_message("Sorry, I couldn't find a team name associated with your request."
                    " Use '/help' to get a list of commands.")

return 'ok', 200

enter image description here

1 个答案:

答案 0 :(得分:0)

  

问题:遍历孩子的孩子
  评论team_info_snapshot = cfm.child('teams').child(team_id).get()生成
的多个实例   [{'accelRating': 96, 'age': 27, 'agilityRating': 91, 'awareRating': 87, 'bCVRating'....etc}]

结果是list中的dict

team_info_snapshot = cfm.child('teams').child(team_id).get()
count = 0
for team in team_info_snapshot:
    print(team) # {'accelRating': 96, 'age': 27, 'agilityRating': 91, ...etc}
    print(team['age']) # 27

    if team['age'] == 27:
        count += 1

返回一个对象列表,可以在每个对象上调用val()和key()。

team_info_snapshot = cfm.child('teams').child(team_id).get()
for team in team_info_snapshot.each():
    print(team.key()) # 0
    print(team.val()) # {"age": 1, "accelRating": 2, ...}
    print(team.val()['age']) # 1