peewee:使用 Model.get 和默认值而不是抛出异常
peewee: using Model.get with a default value instead of throwing an exception
我刚开始使用 peewee ORM 框架,遇到了一些对我来说有点奇怪的行为:
我真的必须在 try/except-clause 中使用 Model.get
才能为我的查询获取默认值吗?
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?'
前五行代码有快捷方式吗?
我能够将它减少到 2 行,但我不确定它是否是一个快捷方式。
results = User.select().where(User.name=="Yellow").limit(1)
user = user if len(results) > 0 else None
来自 Peewee 文档:
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.
为了进一步简化,我建议将上面的行包装到一个更通用的函数中。
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')))
输出
Red
None
我刚开始使用 peewee ORM 框架,遇到了一些对我来说有点奇怪的行为:
我真的必须在 try/except-clause 中使用 Model.get
才能为我的查询获取默认值吗?
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?'
前五行代码有快捷方式吗?
我能够将它减少到 2 行,但我不确定它是否是一个快捷方式。
results = User.select().where(User.name=="Yellow").limit(1)
user = user if len(results) > 0 else None
来自 Peewee 文档:
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.
为了进一步简化,我建议将上面的行包装到一个更通用的函数中。
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')))
输出
Red
None