English 中文(简体)
如果在座标上存在的话,如何草率地检查是否存在物体/工具/可变和同时将其分配给变数?
原标题:How to elegantly check the existence of an object/instance/variable and simultaneously assign it to variable if it exists in python?

我正在利用KallAlchemy来充实一个数据库,我经常需要检查一个矿石在处理之前是否在数据库中存在。 这可能是一个非常规的问题,但我发现自己经常遇到这样的情况:

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...

我知道,这一辛迪加是错误的,但我想解释一下,我就是这样说的。 任何类似方式都会使我感到欣慰。

是否对这一模式采取了一种leg强的做法? 这一问题的目的不仅在于图西语,而且针对每一种类似情况。

披露我的眼睛,击中“你的问题”,等待聪明的人和心脏的原教旨主义者要求某些可能不适当的东西:>;

最佳回答

你们想要执行一个效率高的Exist que

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

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

如果你不希望获得教育,你可以使用cal:

ret = Session.query(exists().where(SomeObject.field==value)).scalar()
问题回答

This has been asked a long time ago but for future visitors a more concise way to check is

 if session.query(model).filter(some_filter).count():
     # do stuff

wrap it on a function (shamelessly stolen from django get_or_create, this doesnt return a tuple though)

get_or_create(model, **kwargs):
    try:
        # basically check the obj from the db, this syntax might be wrong
        object = session.query(model).filter(**kwargs).first()
        return object
    except DoesNotExistException: # or whatever error/exception it is on SQLA
        object = model()
        # do it here if you want to save the obj to the db
        return object

that s it. to use it:

obj = get_or_create(SomeObject, filters)

change the **kwargs to a simple argument (like some_filters) if you want

try to wrap something you often use (wrap them to functions or classes)

thats only pseudo code, there might be syntax error.

EDIT: 强调

我知道这并不是所有一步,但这是可以接受的吗?

my_object = session.query(SomeObject).filter(some_filter).first()
if my_object is None:
    my_object = SomeObject()
#process
from sqlalchemy.orm.util import has_identity

my_object = session.query(SomeObject).get(id) or SomeObject()
# Processing...

# Check if the object exists in the database
if not has_identity(my_object):
    session.add(my_object)

session.commit()

如果需要,可改为过滤器+首先()

if DBSession.query(ObjectType).filter(ObjectType.some_parametter == "This").first() is None:

这是检查是否存在记录的有效一线方法。 这样做是有效的,因为它只贪 gr了第一物体,而且由于先()返回,它可以一行。 没有相应的记录。 希望帮助!

你们可以这样做:

sth = session.query.filter_by().first()
if sth is None:
    ....
else:
    ....

我对此进行了测试。 它运作良好。

这里有一些建议。 如何使用诺德基金会例外?

try:
    existing = dbsession.query(SomeObject).filter_by(value=value).one()
    return existing
except sqlalchemy.orm.exc.NoResultFound:
    obj = SomeObject()

这里的职能是检查是否存在使用Kalchemy的物体。

def exists(obj, **kwargs):
    """" if obj filtered by kwargs exist return it otherwise return None
        obj : is the sql alchemy model object which existence is being checked here.
        **kwargs : (username = user_name, email=user_email)
    """
    db_obj = obj.query.filter_by(**kwargs).first()
    if db_obj is not None:
        return True
    else:
        return False




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签