使用 peewee 检查查询是否存在

check if query exists using peewee

我在 Python 中使用 Peewee 库,我想检查是否存在查询。如果记录不存在,我不想创建记录,所以我不想使用 get_or_create。肯定有比将 try/except 与 get 一起使用更好的解决方案,但我什么也没看到。请让我知道是否有更好的方法。谢谢。

您可以使用 .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

或者,如果您想检查是否一些其他 table 引用此记录,您可以使用 WHERE EXISTS (subquery) 子句。 PeeWee 本身不支持它,但可以轻松构建它:

subquery = Child.select(Param('1')).where(Child.parent == Parent.id)
parents_with_children = Parent.select().where(
    Clause(SQL('EXISTS'), subquery))

相当于下面的SQL:

SELECT * FROM parent
WHERE EXISTS (SELECT 1 FROM child
              WHERE child.parent_id = parent.id);

这里我使用 SELECT 1 作为子查询以避免获取不需要的信息(比如 child.id)。不确定是否真的需要这样的优化。

UPD (2022 年 2 月)

经过5年多的peewee进化,Clauseclass好像没了

以下代码可能有效(虽然我没有机会测试它):

subquery = Child.select(Param('1')).where(Child.parent == Parent.id)
parents_with_children = Parent.select().where(
    NodeList((SQL('EXISTS'), subquery)))

如果您只需要检查是否存在,请使用已接受的答案。

如果您打算使用该记录(如果它存在),您可以使用 Model.get_or_none(),因为这样就无需使用 try/catch,并且如果该记录不存在,则不会创建记录'不存在。

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