1

我正在让 SQLalchemy 通过 python 为我做一些任务。

我可以通过以下示例使其正常工作,但是现在我在从for循环中移动查询调用时被卡住了一段时间:

for instance in session.query(versions_table).filter(versions_table.c.version==Version):

并通过调用表结果之一获得结果:

 existingID = instance.id

id返回表的PK在哪里)

我不能做的是找到一种随意触发查询的方法,或者作为条件语句的结果,例如

if some conditions met:
 do query
 get / process result

我只能通过调用来获取返回值instance.fieldname

谁能指出我哪里出错了,接受我对 SQLalchemy 函数的设置/调用方式并不是 100% 满意。

我想做的是:

for instance in session.query(versions_table).filter(versions_table.c.version==Version):
 if instance.id == True:  #this is not correct
  print instance.id 
 else:
  print "no match"

更完整的脚本:

from sqlalchemy import *
from sqlalchemy.orm import sessionmaker

engine = create_engine('mysql+mysqldb://u:p@localhost/sqlalchtest',
                   echo=False)

metadata = MetaData(bind=engine)
Session = sessionmaker(bind=engine)
versions_table = Table('versions', metadata, autoload=True)

def doVersionGet(sigfile_filename):
 tree = etree.parse(sigfile_filename)
 root = tree.getroot()
 attributes = root.attrib
 if 'DateCreated' in root.attrib:
  DateCreated = (attributes["DateCreated"])
 if 'Version' in root.attrib:
  Version = (attributes["Version"])
 doVersionPush(DateCreated,Version)

def doVersionPush(DateCreated,Version):
 session = Session() 
 for instance in session.query(versions_table).filter(versions_table.c.version==Version):
  existingID = instance.id 
  #this is not really what I want to do here any way, but this will fire the query every time

if __name__ == "__main__":
 path = "location\sub_sig_files"  ##home_subset for tests
 for (path, dirs, files) in os.walk(path):
  for file in files:
   sigfile_filename = str(path)+"\\"+str(file)
   doVersionGet(sigfile_filename) 
4

1 回答 1

4

您可以使用 执行查询Query.all,这将执行查询并返回实例:

instances = session.query(versions_table).filter(versions_table.c.version==Version).all()
于 2012-04-23T07:50:23.763 回答