sqlalchemy flush () 및 삽입 된 ID 가져 오기?
다음과 같이하고 싶습니다.
f = Foo(bar='x')
session.add(f)
session.flush()
# do additional queries using f.id before commit()
print f.id # should be not None
session.commit()
그러나 f.id
이며 None
나는 그것을 시도 할 때. 이 작업을 수행하려면 어떻게해야합니까?
샘플 코드는 그대로 작동해야합니다. SQLAlchemy는 f.id
자동 생성 기본 키 열로 가정하여에 대한 값을 제공해야합니다 . 기본 키 속성은 flush()
생성되는 즉시 프로세스 내에서 채워 지며에 대한 호출 commit()
이 필요하지 않습니다. 따라서 여기에 대한 답은 다음 중 하나 이상에 있습니다.
- 매핑 세부 정보
- 사용중인 백엔드에 이상한 특성이있는 경우 (예 : SQLite는 복합 기본 키에 대해 정수 값을 생성하지 않음)
- 에코를 켤 때 내 보낸 SQL이 말하는 내용
나는 방금 동일한 문제를 겪었고 테스트 후 이러한 답변 중 어느 것도 충분하지 않다는 것을 발견했습니다.
현재 또는 sqlalchemy .6+부터는 매우 간단한 솔루션이 있습니다 (이전 버전에 존재하는지 여부는 알 수 없습니다.
session.refresh ()
따라서 코드는 다음과 같습니다.
f = Foo(bar=x)
session.add(f)
session.flush()
# At this point, the object f has been pushed to the DB,
# and has been automatically assigned a unique primary key id
f.id
# is None
session.refresh(f)
# refresh updates given object in the session with its state in the DB
# (and can also only refresh certain attributes - search for documentation)
f.id
# is the automatically assigned primary key ID given in the database.
그렇게하는 방법입니다.
모두 감사합니다. 열 매핑을 수정하여 문제를 해결했습니다. 나를 위해 autoincrement=True
필요합니다.
유래:
id = Column('ID', Integer, primary_key=True, nullable=False)
수정 후 :
id = Column('ID', Integer, primary_key=True, autoincrement=True, nullable=True)
그때
session.flush()
print(f.id)
괜찮아!
dpb가 제공하는 답변과 달리 새로 고침이 필요하지 않습니다. 일단 플러시하면 id 필드에 액세스 할 수 있으며 sqlalchemy는 백엔드에서 자동으로 생성 된 ID를 자동으로 새로 고칩니다.
I encountered this problem and figured the exact reason after some investigation, my model was created with id as integerfield and in my form the id was represented with hiddenfield( since i did not wanted to show the id in my form). The hidden field is by default represented as a text. once I changed the form to integerfield with widget=hiddenInput()) the problem was solved.
I once had a problem with having assigned 0
to id before calling session.add
method. The id was correctly assigned by the database but the correct id was not retrieved from the session after session.flush()
.
You should try using session.save_or_update(f)
instead of session.add(f)
.
참고URL : https://stackoverflow.com/questions/1316952/sqlalchemy-flush-and-get-inserted-id
'Programing' 카테고리의 다른 글
Https 연결 Android (0) | 2020.08.20 |
---|---|
SQL Server에서 Begin / End Blocks 및 Go 키워드는 언제 사용해야합니까? (0) | 2020.08.20 |
iOS 6 : 일부보기를 세로로 제한하고 다른보기는 회전하도록 허용하려면 어떻게합니까? (0) | 2020.08.20 |
Python에서 2 차원 배열 회전 (0) | 2020.08.20 |
ggplot2에서 "데이터 클래스 비정상"오류를 처리하는 방법은 무엇입니까? (0) | 2020.08.20 |