Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if query exists using peewee

Tags:

python

peewee

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.

like image 372
calthoff Avatar asked Jul 30 '15 03:07

calthoff


2 Answers

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

like image 66
coleifer Avatar answered Sep 18 '22 11:09

coleifer


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
like image 29
Weston Avatar answered Sep 18 '22 11:09

Weston