使用p检查查询是否存在

2024-04-19 09:44:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python中的Peewee库,我想检查是否存在查询。我不想创建一个不存在的记录,所以我不想使用get_或_create。一定有比使用try/except和get更好的解决方案,但是我什么也没看到。如果有更好的办法,请告诉我。谢谢。


Tags: getcreate记录解决方案peeweetryexcept办法
3条回答

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

如果要使用记录(如果它存在),可以使用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

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

或者,如果要检查是否有其他表引用了该记录,可以使用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)。不确定是否真的需要这样的优化。

相关问题 更多 >