Skip to main content
 首页 » 编程设计

python之如何在 Python 中将文档 ID 添加到 firestore 文档

2025年05月04日23sxdcgaq8080

我正在尝试使用 python 将 firestore 上新文档的文档 ID 添加到对象本身,但是它在添加时缩短了字符串,实际上并没有添加相同的 ID。

我已经打印了 ID,它说它应该是一样的。尽管在 Firestore 中有所不同。

doc_ref = db.collection(u'prime_location').document() 
        print('ID: ', doc_ref.id) 
        docId = doc_ref.id 
 
         # set object and push to firebase 
        doc_ref.set({ 
                u'property_id': docId, 
                u'property_address': address, 
                u'number_of_beds': number_beds, 
                u'number_of_baths': number_baths, 
                u'property_rent': property_price, 
                u'post_code': postcode, 
                u'property_photo': property_image, 
            }) 

这方面的一个例子是文档的 ID 是:'aMqwOsjDbOuQmi8PZmot' 但 'property_id' 值显示为:'YU1xd09zak...' 有人知道为什么会发生这种行为吗?

请您参考如下方法:

发生这种情况是因为您生成了一个随机 ID 两次。

doc_ref = db.collection(u'prime_location').document() 
        print('ID: ', doc_ref.id) //generates one id 
        docId = doc_ref.id //generates the second id 

要解决这个问题,您可以通过仅调用一次 doc_ref.id 来生成一个 id,如以下代码行所示:

doc_ref = db.collection(u'prime_location').document() 
        docId = doc_ref.id //generates id 
        print('ID: ', docId) //print the generatd id 

然后在您的代码中进一步简单地使用 docId 变量和 not doc_ref.id 每次调用时都会生成另一个 id。