I have the following tables defined declaratively (very simplified version):
class Profile(Base):
__tablename__ = \'profile\'
id = Column(In
The documentation says I need to use an association object to do this but it's confusing me and I can't get it to work.
That's right. And the Answer class is your association object as it maps to the association table 'answer'.
How do I define the many-to-many relationship for the Profile and Question tables using Answer as the intermediary table?
The code you've presented in your question is correct. It only needs additional information about relationships on the ORM level:
from sqlalchemy.orm import relationship
...
class Profile(Base):
__tablename__ = 'profile'
...
answers = relationship("Answer", backref="profile")
...
class Question(Base):
__tablename__ = 'question'
...
answers = relationship("Answer", backref="question")
...
Also, you shouldn't setup values for profile_id and question_id in your Answer's init function, because it's the ORM that's responsible for setting them accordingly based on you assignments to relationship attributes of your objects.
You may be interested in reading documentation for declarative, especially the part about configuring relationships. Reading about working with related objects may be helpful as well.