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!
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(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).
I got the solution
mdetails = merchant_details.update(
merchant_name=request.form['merchantname'],
first_name=request.form['firstname'],
last_name=request.form['lastname'],
street_1=request.form['street1'],
street_2=request.form['street2'],
state=request.form['state'],
city=request.form['city'],
phone=request.form['phone'],
zipcode=request.form['zip'],
).where(merchant_details.merchant_id==session['userid'])
mdetails.execute()
Anyways Thanks Mark
I searched for this solution too and thanks to #Mark and #Rohit I changed my code (peeweee with PostgreSQL) and is working.
To add a small improve it seems the update will be executed even if you will not use the variable. For me is simpler and a cleaner code:
merchant_details.update(
merchant_name=request.form['merchantname'],
first_name=request.form['firstname'],
last_name=request.form['lastname'],
street_1=request.form['street1'],
street_2=request.form['street2'],
state=request.form['state'],
city=request.form['city'],
phone=request.form['phone'],
zipcode=request.form['zip'],
).where(merchant_details.merchant_id==session['userid']).execute()
Related
I have one label say User,and one property say Email.I am trying to insert one property value based on user input like "abcd#gmail.com" . My code is below
db=Graph("bolt://localhost:1234", user="", password="")
db.evaluate('''Create (u:User) WHERE u.Email=$para1 RETURN u''',
parameters={'para1': arg}))
I am tried also
db.create(Node("User", "Email").__setitem__("Email", arg))
However both is not working.
I have solved my problem.Posting the answer so it may help others.
self.db.evaluate('''Create (u:User) SET u.Email=$para1 RETURN u''',
parameters={'para1': arg})
This question gets me close to what I want to do but I am still in need of further understanding. Django. Q objects dynamicaly generate
I have a view in django that looks to see if any query params have been sent to the url. I am expecting some query objects to have multipule values.
ie. domain.com/?neighborhood=Logan Square&neighborhood=River North
I grab queryparams and put them in a list. I am now trying to iterate through that list and filter through the query params using or logic.
https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q
for this I know I need to use Q objects.
the proper code for this is:
Q(neighborhood='Logan Square') | Q(neighborhood='River North')
so what I need to do is
1 adding a query Q object dynamically and then also adding the | operator dynamically for all objects in the for loop.
You don't need this at all. You can simply use __in:
MyModel.objects.filter(neighborhood__in=request.GET.getlist('neighborhood'))
If I understood your question correctly.
"You may, or may NOT get the query params."?
query = ModelName.objects.none() # setting a Q() instance (maybe skippable)
for a_item in neighbourhood_list:
query |= (Q(neighborhood = a_item))
query = ModelName.objects.filter(query)
You might have to test it, and edit this a little bit, but will do the trick you want.
I am using the Peewee library in Python and I want to check if a query exists. I do not want to create a record if it doesn't exist, so I don't want to use get_or_create. There must be a better solution than to use try/except with get but I don't see anything. Please let me know if there is a better way. Thanks.
You can use .exists():
query = User.select().where(User.username == 'charlie')
if query.exists():
# A user named "charlie" exists.
cool()
http://docs.peewee-orm.com/en/latest/peewee/api.html?highlight=exists#SelectBase.exists
If you just need to check existence use the accepted answer.
If you are going to use the record if it exists you can make use of Model.get_or_none() as this removes the need to use a try/catch and will not create a record if the record doesn't exist.
class User(peewee.Model):
username = peewee.CharField(unique=True)
user = User.get_or_none(username='charlie')
if user is not None:
# found user, do something with it
pass
Alternatively, if you want to check if e.g. some other table refers this record, you can use WHERE EXISTS (subquery) clause. It is not supported natively by PeeWee, but it can be easily constructed:
subquery = Child.select(Param('1')).where(Child.parent == Parent.id)
parents_with_children = Parent.select().where(
Clause(SQL('EXISTS'), subquery))
It is equivalent to the following SQL:
SELECT * FROM parent
WHERE EXISTS (SELECT 1 FROM child
WHERE child.parent_id = parent.id);
Here I used SELECT 1 for subquery to avoid fetching unneeded information (like child.id). Not sure if such optimization is actually required.
UPD (Feb 2022)
After more than 5 years of peewee evolution, it looks like the Clause class is gone.
The following code may work (I didn't have a chance to test it though):
subquery = Child.select(Param('1')).where(Child.parent == Parent.id)
parents_with_children = Parent.select().where(
NodeList((SQL('EXISTS'), subquery)))
I'm inserting/updating objects into a MySQL database using the peewee ORM for Python. I have a model like this:
class Person(Model):
person_id = CharField(primary_key=True)
name = CharField()
I create the objects/rows with a loop, and each time through the loop have a dictionary like:
pd = {"name":"Alice","person_id":"A123456"}
Then I try creating an object and saving it.
po = Person()
for key,value in pd.items():
setattr(po,key,value)
po.save()
This takes a while to execute, and runs without errors, but it doesn't save anything to the database -- no records are created.
This works:
Person.create(**pd)
But also throws an error (and terminates the script) when the primary key already exists. From reading the manual, I thought save() was the function I needed -- that peewee would perform the update or insert as required.
Not sure what I need to do here -- try getting each record first? Catch errors and try updating a record if it can't be created? I'm new to peewee, and would normally just write INSERT ... ON DUPLICATE KEY UPDATE or even REPLACE.
Person.save(force_insert=True)
It's documented: http://docs.peewee-orm.com/en/latest/peewee/models.html#non-integer-primary-keys-composite-keys-and-other-tricks
I've had a chance to re-test my answer, and I think it should be replaced. Here's the pattern I can now recommend; first, use get_or_create() on the model, which will create the database row if it doesn't exist. Then, if it is not created (object is retrieved from db instead), set all the attributes from the data dictionary and save the object.
po, created = Person.get_or_create(person_id=pd["person_id"],defaults=pd)
if created is False:
for key in pd:
setattr(fa,key,pd[key])
po.save()
As before, I should mention that these are two distinct transactions, so this should not be used with multi-user databases requiring a true upsert in one transaction.
I think you might try get_or_create()? http://peewee.readthedocs.org/en/latest/peewee/querying.html#get-or-create
You may do something like:
po = Person()
for key,value in pd.items():
setattr(po,key,value)
updated = po.save()
if not updated:
po.save(force_insert=True)
there's something I'm struggling to understand with SQLAlchamy from it's documentation and tutorials.
I see how to autoload classes from a DB table, and I see how to design a class and create from it (declaratively or using the mapper()) a table that is added to the DB.
My question is how does one write code that both creates the table (e.g. on first run) and then reuses it?
I don't want to have to create the database with one tool or one piece of code and have separate code to use the database.
Thanks in advance,
Peter
create_all() does not do anything if a table exists already, so just call it as soon as you set up your engine or connection.
(Note that if you change your table schema, create_all() will not update it! So you still need "another program" to do that.)
This is the usual pattern:
def createEngine(metadata, dsn, **args):
engine = create_engine(dsn, **args)
metadata.create_all(engine)
return engine
def doStuff(engine):
res = engine.execute('select * from mytable')
# etc etc
def main():
engine = createEngine(metadata, 'sqlite:///:memory:')
doStuff(engine)
if __name__=='__main__':
main()
I think you're perhaps over-thinking the situation. If you want to create the database afresh, you normally just call Base.metadata.create_all() or equivalent, and if you don't want to do that, you don't call it.
You could try calling it every time and handling the exception if it goes wrong, assuming that the database is already set up.
Or you could try querying for a certain table and if that fails, call create_all() to put everything in place.
Every other part of your app should work in the same way whether you perform the db creation or not.