I think the only place I found this behaviour was in the Dataset utility.
Usually, to get a row you would use Model.get.
However, if the row doesn't exist, a DoesNotExist is thrown.
I propose a 'get_or_none' function to return None instead of throwing an error, in this way, you can simply query a record and have nothing if there's no records.
e.g
user = User.get(username == 'razodactyl') # returns User
user = User.get(username == 'not_created_yet') # returns None
I'm currently using this on my 'BaseModel' implementation which is a subclass of 'db.Model' which came from the FlaskDB helper.
class BaseModel(db.Model):
@classmethod
def get_or_none(cls, *query, **kwargs):
try:
return cls.get(*query)
except cls.DoesNotExist:
return None
user = User.select().where(username == 'not-created').first()
That's what I usually do. first() will return a record or None.
Thanks @timster
Most helpful comment
That's what I usually do.
first()will return a record or None.