Peewee: Model.get_or_none

Created on 4 Dec 2016  路  3Comments  路  Source: coleifer/peewee

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

Most helpful comment

user = User.select().where(username == 'not-created').first()

That's what I usually do. first() will return a record or None.

All 3 comments

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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

vkrizan picture vkrizan  路  3Comments

GMaxera picture GMaxera  路  4Comments

lucasrc picture lucasrc  路  5Comments

kadnan picture kadnan  路  3Comments

aellwein picture aellwein  路  3Comments