title: Foreign Key could not be found with SqlAlchemy and PostgreSQL
body: <p>I just started a Flask - SqlAlchemy project and am having some trouble with Foreign Keys.</p>
  
  <p>I have the tables User and Portfolio. Portfolio has a foreign key to user, using username. I set up my model like this.</p>
  
  <pre><code>class User(db.Model):
    __tablename__ = 'portfolio_users'
    __table_args__ = {"schema":"keldan"}
    username = Column(String(), primary_key=True)
    date_added = Column(DateTime())
  
  class Portfolio(db.Model):
    __tablename__ = 'portfolios'
    __table_args__ = {"schema":"keldan"}
    id = Column('pid', Integer(), Sequence('portfolios_pid_seq'), primary_key=True)
    date_added = Column(DateTime())
    name = Column(String())
    username = Column(String(), ForeignKey('portfolio_users.username'))
    user = relationship('User', backref=backref('portfolios', cascade='save-update, merge, delete, delete-orphan'))
  </code></pre>
  
  <p>The error I get when I try to run a simple select all query is:</p>
  
  <pre><code>sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'portfolios.username' could not find table 'portfolio_users' with which to generate a foreign key to target column 'username'
  </code></pre>
  
  <p>The tables are created like this:</p>
  
  <pre><code>CREATE TABLE keldan.portfolio_users
  (
    username text NOT NULL,
    date_added date NOT NULL,
    CONSTRAINT users_pk PRIMARY KEY (username)
  )
  WITH (
    OIDS=FALSE
  );
  
  CREATE TABLE keldan.portfolios
  (
    pid serial NOT NULL,
    username text NOT NULL,
    date_added date NOT NULL,
    name text NOT NULL,
    CONSTRAINT portfolios_pk PRIMARY KEY (pid),
    CONSTRAINT portfolios_fk FOREIGN KEY (username)
        REFERENCES keldan.portfolio_users (username) MATCH SIMPLE
        ON UPDATE NO ACTION ON DELETE NO ACTION
  )
  WITH (
    OIDS=FALSE
  );
  </code></pre>
  
  <p>I have spent the better part of a day trying to figure this out or making workarounds using primaryjoin but nothing seems to work.</p>