简体   繁体   中英

I am trying to get only the value of a field in firestore using python but it returns a key value pair instead

I am linking my application with cloude firestore and I am using python for it and I need to retrive the value "Balance" field for checking if it is valid. but when I try to retrieve it I get outputs like this

{ Balance: 80 }

But I need only the integer/float value of the balance. My code is as follows-

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

# Use the application default credentials
cred = credentials.Certificate("/Users/admin/Downloads/serviceAccountKey.json")
firebase_admin.initialize_app(cred)

db = firestore.client()
user_id= 'my user id in database'
u = 80
userbal_new= u-10
users_ref = db.collection(u'users').document(user_id)

#update balance
#users_ref.update({u'Balance': userbal_new})

#get balance
get_bal= users_ref.get({u'Balance'})
bal = u'{}'.format(get_bal.to_dict())
print (bal)

Because you're using the to_dict function here:

bal = u'{}'.format(get_bal.to_dict())

This is generating a dictionary, you can call the bal dict afterwards like so:

bal['Balance']

Alternatively, make the call in the format (if it's always balance that you want):

bal = u'{}'.format(get_bal.to_dict()['Balance'])

You can specify the field_paths you want returned in the snapshot with the db.collection().document().get() by passing field_paths={}

get_bal = users_ref.get(field_paths={'Balance'}).to_dict()

This will return just the balance in a dictionary:

{ Balance: 80 }

I find the get() easer to read. So if you only want the int.

bal = get_bal.get('Balance')

or

bal = users_ref.get(field_paths={'Balance'}).to_dict().get('Balance')

will return

80

如果你得到 bal = { 'Balance': 80 } 那么为了得到平衡使用 .. print(bal['Balance'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM