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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With