title: SQLAlchemy: How to do many-to-many of table to itself (declarative way)
body: <p>I am trying to define Many to Many relations of users. I followed the docs and the best I got was:</p>
  
  <pre><code>import sqlalchemy as sa
  from sqlalchemy import orm
  from sqlalchemy.ext.declarative import declarative_base
  
  Base = declarative_base()
  
  
  class Friends(Base):
      __tablename__ = 'friends'
      user1_id = sa.Column(sa.ForeignKey('users.id'), primary_key=True)
      user2_id = sa.Column(sa.ForeignKey('users.id'), primary_key=True)
  
  
  class User(Base):
      __tablename__ = 'users'
      id = sa.Column(sa.Integer, primary_key=True)
      name = sa.Column(sa.String(50))
      # many to many
      friends = orm.relationship('User', secondary=Friends, backref=Friends)
  
  u = User(name='someuser')
  </code></pre>
  
  <p>But that would give me </p>
  
  <blockquote>
    <p><strong>"AttributeError: 'Friends' object has no attribute 'foreign_keys"</strong></p>
  </blockquote>
  
  <p>What's wrong?</p>