【问题标题】:python firebase update items using where querypython firebase使用where查询更新项目
【发布时间】:2019-02-27 08:05:22
【问题描述】:

我正在使用带有 firebase 的 python,并且有一个表,我需要更新字段中具有特定值的所有项目,我发现了如何查询具有该值的所有项目 herehere

现在我需要更新我得到的所有物品。

我想做的是使用单个查询来执行单个操作,该操作将使用 where 查询找到正确的项目,并将某个字段更新为某个值,我需要该功能才能保持部分数据一致。

谢谢

【问题讨论】:

  • 您说的是实时数据库还是 Firestore?在这两种情况下,您都无法使用查询更新数据。你必须查询,然后更新。
  • 请发一个答案让我收到

标签: python database firebase


【解决方案1】:

可以做到,但需要更多步骤:

# the usual preparation
import firebase_admin
from firebase_admin import credentials, firestore
databaseURL = {'databaseURL': "https://<YOUR-DB>.firebaseio.com"}
cred = credentials.Certificate("<YOUR-SERVICE-KEY>.json")
firebase_admin.initialize_app(cred, databaseURL)
database = firestore.client()
col_ref = database.collection('<YOUR-COLLECTION>')

# Query generator for the documents; get all people named Pepe
results = col_ref.where('name', '==', 'Pepe').get()
# Update Pepe to José
field_updates = {"name": "José"}
for item in results:
  doc = col_ref.document(item.id)
  doc.update(field_updates)

(我用的是Cloud Firestore,可能实时数据库不一样)

【讨论】:

    【解决方案2】:

    您可以遍历查询并在每次迭代中找到 DocumentReference。

        db = firestore.client()
    
        a= request_json['message']['a']
        b= request_json['message']['b']
        
    
        ref = db.collection('doc').where(a'', u'==', u'a').stream()
        for i in ref: 
            i.reference.update({"c":"c"}) # get the document reference and use it to update\delete ...
    

    【讨论】:

      猜你喜欢
      • 2021-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-17
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多