Search code examples
pythonjsonsqlitepeewee

how to update a table from a JSON loaded object using peewee ORM on python


from schema import db, CustomerTable as GF
db.connect()

#this works
query = GF.update(Priority=88).where(GF.CustomerID==1)
query.execute()

can someone help me with this please? The above code works fine in updating an sqlite database. The bottom doesn't.

#this doesn't work and help needed...

#JSON string
customers = '{ "name":"john john", "mobile":12345678, "email":"john.doe@gmail.com"}'
pycustomers = json.loads(customers)

# print(pycustomers["name"])
for keys in pycustomers:
    print("This is the key: ", keys, "\t\tThis is the value: ", pycustomers[keys])
    query = GF.update({keys: pycustomers[keys]}).where(GF.Mobile==pycustomers["mobile"])

Solution

  • If all the keys of the JSON dict correspond to fields on the model, you can just pass the data right in:

    customers = '{ "name":"john john", "mobile":12345678, "email":"john.doe@gmail.com"}'
    pycustomers = json.loads(customers)
    
    # print(pycustomers["name"])
    nrows = (GF.update(pycustomers)
            .where(GF.Mobile==pycustomers["mobile"])
            .execute())
    

    Docs that may be helpful: