如何确定SQLAlchemy会话是否需要提交?以下是示例代码:
#!/usr/bin/env python
import sys
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relation, validates
DeclBase = declarative_base()
class Parent(DeclBase):
__tablename__ = 'parent'
id = Column('id', Integer, primary_key=True)
name = Column('name', String)
children = relation('Child', back_populates='parent')
def __repr__(self):
return "<Parent(id='%d', name='%s')>" % (self.id, self.name)
def __init__ (self, id, name=''):
self.id = id
self.name = name
class Child(DeclBase):
__tablename__ = 'child'
id = Column('id', Integer, primary_key=True)
name = Column('name', String)
parent_id = Column('parent', Integer, ForeignKey('parent.id'))
parent = relation('Parent', back_populates='children')
def __repr__(self):
return "<Child(id='%d', name='%s')>" % (self.id, self.name)
def __init__ (self, id, parent, name=''):
self.id = id
self.name = name
self.parent_id = parent
## Main()
dbengine = create_engine('postgresql://{}:{}@{}:{}/{}'.format(
'swms-dba', 'swms-dba', 'localhost', 5432, 'swmsdb'),
client_encoding='utf8')
dbsession = sessionmaker(bind=dbengine)()
p1 = Parent(1,'Parent')
dbsession.add(p1)
c1 = Child(1,1,'Child#1')
dbsession.add(c1)
c2 = Child(2,1,'Child#2')
dbsession.add(c2)
print('Before:', dbsession.dirty, dbsession.new, dbsession.deleted)
query = dbsession.query(Parent).filter(Parent.id==1)
if query.count() == 1:
parent=query.one()
print(parent)
for child in parent.children:
print(child)
print('After:', dbsession.dirty, dbsession.new, dbsession.deleted)
dbsession.close()
## End
产生的输出是:
>test.py
Before: IdentitySet([]) IdentitySet([<Parent(id='1', name='Parent')>,
<Child(id='1', name='Child#1')>,
<Child(id='2', name='Child#2')>]) IdentitySet([])
<Parent(id='1', name='Parent')>
<Child(id='1', name='Child#1')>
<Child(id='2', name='Child#2')>
After: IdentitySet([]) IdentitySet([]) IdentitySet([])
如果我在调用sessionmaker()时将autoflush设置为False,则IdentitySets在第二次打印时不会变空。但是,query()并没有任何实例:(看起来像autoflush设置为True,query()触发刷新,清空IdentitySet