How to use Update query in Flask Peewee?

Rohit Dhiman picture Rohit Dhiman · Oct 8, 2013 · Viewed 8k times · Source

Hi I am using Flask Peewee and trying to update merchant_details model but it is not working. Following is the error I am getting:

AttributeError: 'SelectQuery' object has no attribute 'update'

mdetails = merchant_details.filter(merchant_details.merchant_id==session['userid']).update(
         merchant_name=request.form['merchantname'],
          first_name=request.form['firstname'],
          last_name=request.form['lastname'],
        )

Please Help!

Answer

Mark Hildreth picture Mark Hildreth · Oct 8, 2013

First, it looks like you are using pre-2.0 syntax (the filter method is now deprecated). I'd recommend looking at the docs for info on the latest version.

Typically, you do not "update a query". The two main ways of accomplishing this is are...

1.) Use a query to retrieve an object, then use the save() method to update the object. For example...

mdetails = MerchantDetails.select().where(MerchantDetails.id == 42).get()
mdetails.name = 'new name'
mdetails.save() # Will do the SQL update query.

2.) Use a SQL update statement...

q = MerchantDetails.update(MerchantDetails.name='new name')
    .where(MerchantDetails.id == 42)
q.execute() # Will do the SQL update query.

Both of these, in essence, accomplish the same thing. The first will make two queries o the database (one to SELECT the record, another to UPDATE the record), while the second will only use one SQL call (to UPDATE the record).