如何检查 SqlAlchemy returns 中的查询是否为空结果?
How to check if query in SqlAlchemy returns empty result?
我想执行这样的查询:
query = users.select().where(users.column.id == id)
res = await database.execute(query)
然后我想通过检查 res
添加一些错误处理。 if not res
好像不对。执行此操作的正确方法是什么?
您可以尝试从查询中获取第一个对象并像这样检查它是否为 Null
result = users.select().where(users.column.id == id).first()
if not result:
print('query is empty')
另一种编辑代码的方法是
res = query.first()
然后检查它是否为 Null
根据您的查询的复杂性,将其包装在 SELECT EXISTS(...)
中可能比 SELECT ... LIMIT 1
更便宜,正如 Antonio 所描述的那样。 PostgreSQL 可能知道以相同的方式处理这些查询,但根据 this answer,并非所有 DBMS 都可以这样做。
这种解决方案的美妙之处在于,它一找到任何结果就存在——它做的工作尽可能少,因此成本也尽可能低。在 SQLAlchemy 中是 sa.select([sa.exists(query)])
我想执行这样的查询:
query = users.select().where(users.column.id == id)
res = await database.execute(query)
然后我想通过检查 res
添加一些错误处理。 if not res
好像不对。执行此操作的正确方法是什么?
您可以尝试从查询中获取第一个对象并像这样检查它是否为 Null
result = users.select().where(users.column.id == id).first()
if not result:
print('query is empty')
另一种编辑代码的方法是
res = query.first()
然后检查它是否为 Null
根据您的查询的复杂性,将其包装在 SELECT EXISTS(...)
中可能比 SELECT ... LIMIT 1
更便宜,正如 Antonio 所描述的那样。 PostgreSQL 可能知道以相同的方式处理这些查询,但根据 this answer,并非所有 DBMS 都可以这样做。
这种解决方案的美妙之处在于,它一找到任何结果就存在——它做的工作尽可能少,因此成本也尽可能低。在 SQLAlchemy 中是 sa.select([sa.exists(query)])