Search code examples
pythonpeewee

peewee: using Model.get with a default value instead of throwing an exception


I just started working with the peewee ORM framework and encountered some kind of behaviour which seems a little strange to me:

Do I really have to use Model.get inside a try/except-clause to get a default value for my query?

user = None
try:
  user = User.get(User.phone_number == phone_number)
except User.DoesNotExist:
  pass

if user:
  print u'Hello, {}!'.format(user.first_name)
else:
  print u'Who are you?'

Is there a shortcut for the first five lines of code?


Solution

  • I was able to reduce it to 2 lines, but I'm not sure that it is a shortcut.

    results = User.select().where(User.name=="Yellow").limit(1)
    user = user if len(results) > 0 else None
    

    From Peewee documentation:

    The get() method is shorthand for selecting with a limit of 1. It has the added behavior of raising an exception when no matching row is found. If more than one row is found, the first row returned by the database cursor will be used.


    To further simplify, I would recommend wrapping the line above into a more generic function.

    def get_without_failing(Model, query):
        results = Model.select().where(query).limit(1)
        return results[0] if len(results) > 0 else None
    
    print(get_without_failing(User, (User.name=='Red')).name)
    print(get_without_failing(User, (User.name=='Yellow')))
    

    Output

    Red
    None