객체 / 인스턴스 / 변수의 존재를 우아하게 확인하고 파이썬에 존재하는 경우 변수에 동시에 할당하는 방법은 무엇입니까?
SQLAlchemy를 사용하여 데이터베이스를 채우고 있으며 처리하기 전에 orm 개체가 데이터베이스에 있는지 종종 확인해야합니다. 이것은 틀에 얽매이지 않는 질문 일 수 있지만,이 패턴을 자주 접하게되었습니다.
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...
이 구문이 잘못되었음을 알고 있지만이 예제가 의미하는 바를 설명하고 싶습니다. 동등한 방법으로 나를 행복하게 만들 것입니다.
이 패턴에 대한 우아한 파이썬 접근 방식이 있습니까? 이 질문은 SQLAlchemy뿐만 아니라 각각의 동등한 시나리오를 목표로합니다.
내 눈을 감고 "Post your question"을 누르고 똑똑한 사람들과 pythonistas가 부적절 할 수있는 무언가를 묻기 위해 나를 사냥하기를 기다립니다. ;-)
효율적으로 Exist 쿼리를 실행하려는 경우
(ret, ), = Session.query(exists().where(SomeObject.field==value))
Mike Bayer는 그의 블로그 게시물에서 설명합니다.
http://techspot.zzzeek.org/2008/09/09/selecting-booleans/
결과로 튜플을 가지지 않으려면 스칼라를 사용할 수 있습니다.
ret = Session.query(exists().where(SomeObject.field==value)).scalar()
이것은 오래 전에 요청되었지만 향후 방문자에게 더 간결하게 확인하는 방법은
if session.query(model).filter(some_filter).count():
# do stuff
그것을 함수에 감싼다 (django get_or_create에서 뻔뻔스럽게 훔 쳤지 만 튜플을 반환하지 않음)
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
그게 다야. 그것을 사용하려면 :
obj = get_or_create(SomeObject, filters)
**kwargs
원하는 경우 간단한 인수 (예 : some_filters)로 변경하십시오.
자주 사용하는 것을 랩핑하십시오 (함수 또는 클래스로 랩핑하십시오)
의사 코드 일뿐 구문 오류가있을 수 있습니다.
EDIT: emphasize
I know it's not all one step, but is this acceptable?
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()
.get() can be replaced with a filter() + first() if needed
if DBSession.query(ObjectType).filter(ObjectType.some_parametter == "This").first() is None:
This is an efficient one line way of checking whether a record exists. It is efficient because it only grabs the first object, and it can be on one line because first() returns None when there are no matching records. Hope that helps!
Some nice suggestions here. How about using the NoResultFound exception?
try:
existing = dbsession.query(SomeObject).filter_by(value=value).one()
return existing
except sqlalchemy.orm.exc.NoResultFound:
obj = SomeObject()
You can use this:
sth = session.query.filter_by().first()
if sth is None:
....
else:
....
I have tested it.It works well.
'IT박스' 카테고리의 다른 글
함수에서 char *와 char []를 반환하는 것의 차이점은 무엇입니까? (0) | 2020.11.15 |
---|---|
PHP의 Structs 데이터 유형? (0) | 2020.11.14 |
mysql : 소스 오류 2? (0) | 2020.11.14 |
사용자 정의 UserControl을 대화 상자로 어떻게 표시합니까? (0) | 2020.11.14 |
사용자가 Android의 갤러리에서 사진을 찍거나 이미지를 선택할 수 있도록하는 단일 의도 (0) | 2020.11.14 |