首页 > 解决方案 > “DocumentReference”对象没有属性“to_dict”

问题描述

我正在使用 python3 来查询 firestore 上的数据库。我的代码如下:

def getWebConsultReData():
    collection = db.collection("webconsult_threescrap").where("compositeKey", "==", "10004-5327729026")
    docs = [snapshot.reference for snapshot in collection.stream()]
    mDictList = []
    print(docs)
    for doc in docs:   
        formattedData = doc.to_dict()
getWebConsultReData()

但是,我收到以下错误:

[<google.cloud.firestore_v1.document.DocumentReference object at 0x7f2a183413c8>]
Traceback (most recent call last):

  File "<ipython-input-42-172d5765da1d>", line 9, in <module>
    getWebConsultReData()

  File "<ipython-input-42-172d5765da1d>", line 7, in getWebConsultReData
    formattedData = doc.to_dict()

AttributeError: 'DocumentReference' object has no attribute 'to_dict'

我确定的是:过滤器是有效的,事实上,下面的快照显示了 GUI 的确切语法 在此处输入图像描述

该文件也存在。有人可以帮帮我吗?非常感谢你!

标签: python-3.xgoogle-cloud-firestore

解决方案


您的问题是,在错误点,docsDocumentReferences 数组而不是 s 数组,DocumentSnapshot因为您删除了几行的所有其他数据。 DocumentReference仅给出文档的路径,它不包含文档的全部数据。

要做一些等效的事情(收集一个数组DocumentReferences但也可以访问实际文档),您需要执行以下操作:

def getWebConsultReData():
    collection = db.collection("webconsult_threescrap").where("compositeKey", "==", "10004-5327729026")
    docs = []
    for doc in collection.stream():   
        formattedData = doc.to_dict()
        print(formattedData)
        docs.append(doc.reference)
    print(docs)
getWebConsultReData()

如果有帮助,您还可以查看文档中有关如何从集合中获取多个文档的示例。


推荐阅读