【问题标题】:Cloud Firestore - Python - Performing simple Where query always returns Query objectCloud Firestore - Python - 执行简单的 Where 查询始终返回 Query 对象
【发布时间】:2019-04-09 12:52:59
【问题描述】:

我知道这个问题可能听起来很傻,但是如何使用 Firebase Admin SDK (Cloud Firestore) 和 Python 正确查询数据?

是的,我已经阅读了这里的文档:

我的数据库:

我的代码:

existing_post = db.collection(u'posts').where(u'id', u'==', u'BpzIbkqAkk0').get()
print(existing_post)

我也尝试省略 .get() 方法,但每次都得到相同的结果。

我得到的只是

<google.cloud.firestore_v1beta1.query.Query object at 0x10e7aab00>

有什么想法吗?

【问题讨论】:

  • 可能是[x for x in existing_post]?
  • 您需要遍历结果并在每个元素上调用“to_dict()”,如下所述:firebase.google.com/docs/firestore/query-data/…
  • 感谢@Gerardo,它确实在循环后工作。我将在下面发布答案。

标签: python firebase google-cloud-firestore


【解决方案1】:

@Gerardo 的评论将我引向了正确的方向。这是工作代码:

existing_posts = db.collection(u'posts').where(u'id', u'==', u'BpzIbkqAkk0').get()
for post in existing_posts:
    print(u'{} => {}'.format(post.id, post.to_dict()))

【讨论】:

  • 你能告诉我如何从集合中检索所有文档吗?
【解决方案2】:

您必须使用to_dict() 将生成器对象转换为字典格式。 然后,您可以轻松访问所需的任何值。

existing_posts = db.collection(u'posts').document(u'id').get()
result=existing_posts.to_dict()
id='BpzIbkqAkk0'
result_id=result[id]

试试这个可能对你有帮助。

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 2021-10-12
    • 1970-01-01
    • 1970-01-01
    • 2012-11-30
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2018-03-20
    相关资源
    最近更新 更多