title: Declaring Foreign Keys (of existing table) in SQLAlchemy
body: <p>I am back and this time I have a question about SQLAlchemy.</p>
  
  <p>Say I have the following table in some MySQL db:</p>
  
  <pre><code>table Table1 (
  id1 
  id2
  primary key(id1, id2)
  id1 references Table2.id
  id2 references Table3.id
  )
  </code></pre>
  
  <p>I'd like to map it using SQLAlchemy, and so I try the following:</p>
  
  <pre><code>table_1 = Table('Table1', metadata, Column('id1', INTEGER, ForeignKey('Table2.id'),primary_key=True), Column('id2', INTEGER, ForeignKey('Table3.id'),primary_key=True),autoload=True)
  
  class Table_1(object):
  pass
  
  mapper(Table_1, table_1)
  </code></pre>
  
  <p>I tried it, but SQLAlchemy is saying that it cannot find the table with which to establish a relationship. I have tried using an existing database and mapping it with SQLAlchemy and it worked, but it was a simple, test db. It had no foreign keys in it. I think I am lacking some other lines to establish the relationship between the parent table and the child, but looking at the tutorials I've seen aren't helping me that much.</p>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>Thanks. </p>
  
  <p>UPDATE:</p>
  
  <p>So this is a snippet of the code that I have made to 'connect and map' to my MySQL DB:</p>
  
  <pre><code>from sqlalchemy import *
  from sqlalchemy.ext.declarative import declarative_base
  from sqlalchemy.orm import mapper, sessionmaker
  
  from portal.model import DeclarativeBase, metadata, DBSession
  
  bioentry_ec = Table('BioEntry_EC', metadata, Column("bioentry_id", INTEGER, ForeignKey("bioentry.bioentry_id", ondelete='CASCADE')), Column("ec_id", INTEGER, ForeignKey("EC.id", ondelete='CASCADE')), autoload=True)
  
  ec = Table('EC', metadata, Column("id", INTEGER, primary_key=True), autoload=True)
  
  bioentry = Table('bioentry', metadata, Column("bioentry_id", INTEGER, primary_key=True), Column("biodatabase_id", INTEGER, ForeignKey("biodatabase.biodatabase.id", ondelete='CASCADE')), autoload=True)
  
  biodatabase = Table('biodatabase', metadata, Column("biodatabase_id", INTEGER, primary_key=True), autoload=True)
  
  
  class BioEntryEC(object):
          pass
  
  class EC(object):
      pass
  
  class Biodatabase(object):
      pass
  
  class Bioentry(object):
      pass
  
  mapper(BioEntryEC, bioentry_ec)
  mapper(Biodatabase, biodatabase)
  mapper(Bioentry, bioentry)
  mapper(EC, ec)
  </code></pre>
  
  <p>So these are some of the mappings. I am not sure if I am declaring the Foreign keys incorrectly, or if there is something missing in my code. Take note that the keys in the bioentry_ec table compose a composite key.</p>
  
  <p>When I run turbogears, it tells me that it cannot find biodatabase, even though I have declared it along with the other tables. Am I doing something wrong in my code?</p>
  
  <p>Thanks for any help on this.</p>