I can create a new document (with auto generated ID), and store a reference to it like this:
my_data = {"key": "value"}
doc_ref = db.collection(u'campaigns').add(my_data)
I can access the data itself like:
print (doc_ref[0]) # prints {"key": "value"}
But when I try to access the doc_ref ID, I am unable to:
# All of these throw attribute errors
doc_ref.get()
doc_ref.data()
doc_ref.id
There are other posts which suggest how to do this in Javascript, but none which work for the Python SDK!
How can I access the generated ID of a document I created?
Set the data of a document within a collection, explicitly specifying a document identifier. Add a new document to a collection. In this case, Cloud Firestore automatically generates the document identifier. Create an empty document with an automatically generated identifier, and assign data to it later.
Just enter a document path in the dedicated field and click the button “Get Subcollections”: If the document has one or more subcollections the page will display their id(s). If the document at the path does not exist or if it does not have any subcollection, the Cloud Function will return an empty array.
The documentation is unclear, but I finally got it to work:
doc_ref = db.collection(u'campaigns').document()
doc_ref.set(my_data)
print(doc_ref.id)
To get ID after save on Python:
This will return for instance some id like wlJQKyVDsIIpX0x3NBmt
doc_ref = db.collection('promotions').add(data)
return doc_ref[1].id
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