SQLAlchemy 在具有关联的多对多关系中插入数据 Table

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

我见过几个类似的问题,但 none 非常一针见血。本质上,我在使用 SQLAlchemy 的 Flask 应用程序中有三个 table 模型 Center()Business()CenterBusiness()。目前我正在以这种方式添加到所述关系中:

biz = Business(typId=form.type.data, name=form.name.data,
               contact=form.contact.data, phone=form.phone.data)
db.session.add(biz)
db.session.commit()

assoc = CenterBusiness(bizId=biz.id, cenId=session['center'])
db.session.add(assoc)
db.session.commit()

如您所见,这有点难看,而且我知道有一种方法可以一次性完成定义的关系。我在 SQLAlchemy 的文档上看到他们对使用这样的 table 进行了解释,但我似乎无法让它工作。

#Directly from SQLAlchemy Docs
p = Parent()
a = Association(extra_data="some data")
a.child = Child()
p.children.append(a)

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

不幸的是,这似乎并没有起到作用...任何帮助将不胜感激,下面我已经发布了所涉及的模型。

class Center(db.Model):
    id = db.Column(MEDIUMINT(8, unsigned=True), primary_key=True,
                   autoincrement=False)
    phone = db.Column(VARCHAR(10), nullable=False)
    location = db.Column(VARCHAR(255), nullable=False)
    businesses = db.relationship('CenterBusiness', lazy='dynamic')
    employees = db.relationship('CenterEmployee', lazy='dynamic')

class Business(db.Model):
    id = db.Column(MEDIUMINT(8, unsigned=True), primary_key=True,
                   autoincrement=True)
    typId = db.Column(TINYINT(2, unsigned=True),
                      db.ForeignKey('biz_type.id',
                                    onupdate='RESTRICT',
                                    ondelete='RESTRICT'),
                      nullable=False)
    type = db.relationship('BizType', backref='businesses',
                           lazy='subquery')
    name = db.Column(VARCHAR(255), nullable=False)
    contact = db.Column(VARCHAR(255), nullable=False)
    phone = db.Column(VARCHAR(10), nullable=False)
    documents = db.relationship('Document', backref='business',
                                lazy='dynamic')

class CenterBusiness(db.Model):
    cenId = db.Column(MEDIUMINT(8, unsigned=True),
                      db.ForeignKey('center.id',
                                    onupdate='RESTRICT',
                                    ondelete='RESTRICT'),
                      primary_key=True)
    bizId = db.Column(MEDIUMINT(8, unsigned=True),
                      db.ForeignKey('business.id',
                                    onupdate='RESTRICT',
                                    ondelete='RESTRICT'),
                      primary_key=True)
    info = db.relationship('Business', backref='centers',
                           lazy='joined')
    archived = db.Column(TINYINT(1, unsigned=True), nullable=False,
                         server_default='0')

我能够让它工作,我的问题在于以下代码(错误以粗体显示):

#My Version Using my Tables
center = 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()

正如我在问题中的评论中所解释的:

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.

我仍然会接受任何更新and/or更好的处理这种情况的方法,尽管我认为这是当时最好的方法。

下面的例子可以帮助你 更多详情 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 = name

class 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_key

class 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)