本文介绍了如何优雅地检查对象/实例/变量的存在并同时将其分配给变量(如果它存在于 python 中)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 SQLAlchemy 来填充数据库,并且经常需要在处理之前检查数据库中是否存在 orm 对象.这可能是一个非常规的问题,但我发现自己经常遇到这种模式:

I am using SQLAlchemy to populate a database and often I need to check if a orm object exists in a database before processing. This may be an unconventional question, but I found myself encountering this pattern often:

my_object = session.query(SomeObject).filter(some_fiter).first()
if my_object: # Mostly in databases...
    # Juchee it exists
    # process
else:
    # It does not exist. :-(
    my_object = SomeObject()
    # process

梦想是这样的:

if my_object = session.query(someObject).blabla.first():
    # if my_object is None this scope is left alone
    # if my_object is not None I can work with my_object here...

我知道,这个语法是错误的,但我想解释一下这个例子的意思.任何等效的方式都会让我高兴.

I know, that this syntax is wrong, but I wanted to explain, what I mean by this example. Any equivalent way would make me happy.

这种模式有没有优雅的 Python 方法?这个问题不仅针对 SQLAlchemy,还针对每个等效场景.

Is there an elegant python approach for this pattern? This question aims not only at SQLAlchemy, but to each equivalent scenario.

闭上眼睛点击发布你的问题",然后用心等待聪明人和pythonistas来追捕我,因为我问了一些可能不合适的问题 ;-)

推荐答案

你想要高效地执行 Exist 查询

You want to execute a Exist query to be efficient

(ret, ), = Session.query(exists().where(SomeObject.field==value))

Mike Bayer 在他的博文中解释:
http://techspot.zzzeek.org/2008/09/09/selecting-布尔值/

Mike Bayer explain it in his blog post:
http://techspot.zzzeek.org/2008/09/09/selecting-booleans/

如果你不想得到一个元组,你可以使用标量:

You can use scalar if you don't want to have a tuple as result:

ret = Session.query(exists().where(SomeObject.field==value)).scalar()

这篇关于如何优雅地检查对象/实例/变量的存在并同时将其分配给变量(如果它存在于 python 中)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 16:04