要调用Firestore的孙子数据,您可以使用以下代码示例:
from google.cloud import firestore
# 初始化Firestore客户端
db = firestore.Client()
# 获取孙子数据
def get_grandchild_data(collection, document, grandchild_collection, grandchild_document):
# 获取孙子文档的引用
grandchild_ref = db.collection(collection).document(document)\
.collection(grandchild_collection).document(grandchild_document)
# 获取孙子文档的数据
grandchild_data = grandchild_ref.get().to_dict()
if grandchild_data:
return grandchild_data
else:
return None
# 示例用法
collection = 'users'
document = 'user1'
grandchild_collection = 'posts'
grandchild_document = 'post1'
data = get_grandchild_data(collection, document, grandchild_collection, grandchild_document)
if data:
print(f"孙子文档的数据:{data}")
else:
print("未找到孙子文档的数据")
在上面的代码中,我们首先初始化了一个Firestore客户端,然后定义了一个get_grandchild_data
函数,该函数接收四个参数:集合名称,文档名称,孙子集合名称和孙子文档名称。
在函数内部,我们首先获取孙子文档的引用,然后使用get()
方法获取孙子文档的数据。如果存在孙子文档,则将其转换为字典并返回该数据。否则,返回None
。
在示例用法中,我们指定了集合名称、文档名称、孙子集合名称和孙子文档名称,并调用get_grandchild_data
函数来获取孙子文档的数据。如果数据存在,则打印出来;否则,打印未找到数据的消息。
请确保您已经安装了google-cloud-firestore
库,并且已经正确设置了Firestore的凭据。