Jay Gattuso
Jay Gattuso

Reputation: 4130

Python / SQLalchemy - how to trigger a query?

I am working at getting SQLalchemy to do some tasks for me via python.

I can sort of get it working by following examples, but I have been stuck for a while now on moving the query call from a for loop:

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

and getting result by calling one of the table results:

 existingID = instance.id

(where id is the PK for the returning table)

What I can't do is finding a way of firing the query at will, or as a result of a conditional statement, e.g.

if some conditions met:
 do query
 get / process result

I can only get the returned values by calling instance.fieldname

Could anyone point me to where I am going wrong, accepting that I'm not really 100% comfortable with how the SQLalchemy functions are setup/called.

What I want to do is along the lines of:

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"

fuller script:

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) 

Upvotes: 1

Views: 1686

Answers (1)

van
van

Reputation: 77082

You can execute the query with Query.all, which will execute the query and return the instances:

instances = session.query(versions_table).filter(versions_table.c.version==Version).all()

Upvotes: 4

Related Questions