簡體   English   中英

SQLAlchemy使用關聯表以多對多關系插入數據

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

我已經看到了一些與此類似的問題,但是沒有一個問題在頭上很明顯。 基本上我在使用SQLAlchemy的Flask應用程序中有三個表模型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的文檔中看到他們對使用這樣的表有一個解釋,但我似乎無法讓它工作。

#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()

正如我在問題中的評論所解釋的那樣:

好吧我的問題是我沒有使用我在CenterBusiness模型中的關系鍵“info”來定義附加的關聯。 我說的是center.business認為在這種情況下商業這個詞是任意的。 但是,我需要實際引用這種關系。 因此,我在CenterBusiness中設置的相應密鑰就是信息。

我仍然會接受任何更新和/或更好的方法來處理這種情況,雖然我認為這是當時最好的路線。

下面的例子可以幫助你更多細節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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM