SQLAlchemy Inserting Data in a Many-to-Many Relationship with Association Table SQLAlchemy Inserting Data in a Many-to-Many Relationship with Association Table flask flask

SQLAlchemy Inserting Data in a Many-to-Many Relationship with Association Table


I was able to get this working, my problem lied in the following bit of code (error in bold):

#My Version Using my Tablescenter = Center.query.get(session['center']assoc = CenterBusiness()**assoc.info** = Business(typId=form.type.data, name=form.name.data,                          contact=form.contact.data, phone=form.phone.data)center.businesses.append(assoc)db.session.commit()

As explained in my comment in the question:

Alright my issue was that I was not using the relationship key "info" I have in my CenterBusiness model to define the appended association. I was saying center.business thinking that the term business in that case was arbitrary. However, I needed to actually reference that relationship. As such, the appropriate key I had setup already in CenterBusiness was info.

I will still accept any updates and/or better ways to handle this situation, though I think this is the best route at the time.


below example can help umore details http://docs.sqlalchemy.org/en/latest/orm/extensions/associationproxy.html

class User(Base):     __tablename__ = 'user'     id = Column(Integer, primary_key=True)     name = Column(String(64))     # association proxy of "user_keywords" collection     # to "keyword" attribute     keywords = association_proxy('user_keywords', 'keyword')     def __init__(self, name):         self.name = nameclass UserKeyword(Base):     __tablename__ = 'user_keyword'     user_id = Column(Integer, ForeignKey('user.id'), primary_key=True)     keyword_id = Column(Integer, ForeignKey('keyword.id'), primary_key=True)     special_key = Column(String(50))      # bidirectional attribute/collection of "user"/"user_keywords"      user = relationship(User,            backref=backref("user_keywords",                            cascade="all, delete-orphan")        )    # reference to the "Keyword" object    keyword = relationship("Keyword")    def __init__(self, keyword=None, user=None, special_key=None):        self.user = user        self.keyword = keyword        self.special_key = special_keyclass Keyword(Base):   __tablename__ = 'keyword'   id = Column(Integer, primary_key=True)   keyword = Column('keyword', String(64))  def __init__(self, keyword):      self.keyword = keyword  def __repr__(self):       return 'Keyword(%s)' % repr(self.keyword)