SQLAlchemy Inserting data in a many-to-many relationship with an association table

I saw several questions like this, but none of them hit a nail on the head. Essentially, I have three table models Center(), Business()and CenterBusiness()in a Flask application using SQLAlchemy. I am currently adding to the above relationships as follows:

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

As you can see, this is a little ugly, and I know that there is a way to do this with one hit with attitude as they are defined. I see that in the SQLAlchemy docs there is an explanation of how to work with such a table, but I cannot get it to work.

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

Unfortunately this doesn't seem to do the trick ... Any help would be greatly appreciated, and below I posted related models.

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')
+4
2

, ( ):

#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 . , . , . , . , , - .

- / , , .

+1

u 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)
0

Source: https://habr.com/ru/post/1622264/


All Articles