[英]Firebase Firestore: get generated ID of document (Python)
I can create a new document (with auto generated ID), and store a reference to it like this:我可以创建一个新文档(使用自动生成的 ID),并像这样存储对它的引用:
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:但是当我尝试访问 doc_ref ID 时,我无法:
# 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! 还有其他帖子建议如何在 Javascript 中执行此操作,但没有一个适用于 Python SDK!
How can I access the generated ID of a document I created?如何访问我创建的文档的生成 ID?
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:在 Python 上保存后获取 ID:
This will return for instance some id like wlJQKyVDsIIpX0x3NBmt例如,这将返回一些 id,如wlJQKyVDsIIpX0x3NBmt
doc_ref = db.collection('promotions').add(data)
return doc_ref[1].id
You can get the id from document even before set method is called您甚至可以在调用 set 方法之前从文档中获取 id
doc_ref = db.collection(u'campaigns').document()
id = doc_ref.id
Then do to save:然后做保存:
doc_ref(my_data)
Documentation is very limited on this, but I managed to figure it out through trial and error.文档对此非常有限,但我设法通过反复试验弄清楚了。
If you want to use add
method as the question indicates, instead of a document reference together with a set
method, try:如果您想使用问题所示的add
方法,而不是将文档引用与set
方法一起使用,请尝试:
my_data = {"key": "value"}
response = db.collection(u'campaigns').add(my_data)
id = response[1].id
data = response[1].get().to_dict()
Firestore response when using add
method contains a tuple:使用add
方法时的 Firestore 响应包含一个元组:
DatetimeWithNanoseconds
object - contains the time the document was created DatetimeWithNanoseconds
对象 - 包含文档的创建时间id
and a document snapshot, from which you can extract the document data by chaining get()
and to_dict()
. Firestore 文档引用包含id
和文档快照,您可以通过链接get()
和to_dict()
从中提取文档数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.