如何在Python中按ID排序获取Firestore数据?
Python Firestore 使用 orderBy() 排序的正确方法
核心逻辑:orderBy() 是查询构建方法,必须在 get() 之前调用——get() 是执行查询并返回结果的方法,它返回的 QuerySnapshot 对象没有 orderBy() 方法,所以你之前写的 .get().orderBy() 顺序完全颠倒了。
以下是具体用法示例:
- 单字段升序排序(默认规则为升序)
比如按create_time字段正序排列:
# 正确写法 docs = firestoreDb.collection(u'Messages').orderBy(u'create_time').get() messages_list = list(docs)
- 单字段降序排序
如果要按字段倒序排列,需要指定direction参数:
from google.cloud.firestore import Direction docs = firestoreDb.collection(u'Messages').orderBy(u'create_time', direction=Direction.DESCENDING).get() messages_list = list(docs)
- 多字段排序
可以链式调用多个orderBy(),按调用顺序依次进行排序:
# 先按 category 升序,再按 create_time 降序 docs = firestoreDb.collection(u'Messages')\ .orderBy(u'category')\ .orderBy(u'create_time', direction=Direction.DESCENDING)\ .get() messages_list = list(docs)
注意事项
- 单字段排序Firestore会自动创建索引,但多字段排序需要手动在Firestore控制台创建复合索引,否则会触发查询报错。
- 排序字段名必须和Firestore文档中的字段完全一致,Firestore字段名区分大小写。
内容的提问来源于stack exchange,提问作者Tuğberk Yıldırım
相关产品推荐
相关产品推荐

