經過各種研究和測驗,我決定在這里寫。我正在用 Python 構建 API,并且正在使用 Firebase-Admin SDK。在 Firestore 上,我有一個包含許多集合和子集合的資料庫,通過此代碼,我可以獲取最終集合中存在的檔案。我的問題/疑問是如何獲取集合名稱。具體來說,我想獲取檔案中存在的所有集合的名稱。我的代碼:
collections = firestore.collection('schools').document(regione).collection(provincia).document(comune).collections()
for collection in collections:
for doc in collection.stream():
print(f'{doc.id} => {doc.to_dict()}')
結果:0 => {'INFORMATICA': {'1C ART': 'test'}} school_info => {'school_name': 'Test school 1', 'indirizzo': 'Address 1'}
0 => {' INFORMATICA': {'3C ART': 'ggf8'}}
1 => {'TELECOMUNICAZIONI': {'4C TEL': '26753g'}}
school_info => {'school_name': 'Test school 2', 'indirizzo': 'Address 2'}
相反,我只想獲取集合的名稱,而不會通過輸入所有子集合來多載資料庫:
Test school 1
Test school 2
我想澄清一下,我已經在網路上進行了一些研究,但我還沒有為 Python 中的 admin sdk 找到任何解決方案。提前致謝
我的結構:
Schools (collection) -> Lombardia (document) -> Milan (collection) -> Milan (document) -> Test School 1 (collection) -> 0 (document) -> various field
uj5u.com熱心網友回復:
在您的示例代碼中,Test School 1并且是檔案Test School 2內的子集合。Milan如果您需要從中獲取所有這些子集合的名稱Milan,您可以像以前一樣呼叫該collections()方法,因為這將回傳特定參考位置(在本例中為 Milan 檔案)中所有集合的迭代器。
迭代器的型別是CollectionReference,并且這個類具有 的方便屬性id,它只回傳集合名稱,而無需從集合本身獲取任何檔案。我根據您的結構快速設定了一個測驗來顯示這一點:
fire_db = firestore.client()
collections = fire_db.collection("Schools").document("Lombardia").collection("Milan").document("Milan").collections()
for collection in collections:
print(collection.id) # Gets id property of each iterated collection reference
輸出:
Test School 1
Test School 2
假設您想使用元資料檔案school_info從那里獲取名稱。在這種情況下,您可以通過使用每個CollectionReference迭代來獲取該特定檔案來訪問該檔案,并school_name從該檔案中獲取該檔案(產生與上述相同的輸出):
fire_db = firestore.client()
collections = fire_db.collection("Schools").document("Lombardia").collection("Milan").document("Milan").collections()
for collection in collections:
print(collection.document("school_info").get().get("school_name")) # Fetches each school_info document, and then retrieves the school_name
uj5u.com熱心網友回復:
您嘗試做的可能表明資料結構并不是最好的(從長遠來看,最好重新考慮它)。但這里有一篇關于這個主題的文章。文章中列出的所有解決方案都比較老套。但我認為目前沒有其他方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425741.html
