[已解决]Flask Incompatible collection type: 类名 is not list-like

BUG

Incompatible collection type: 类名 is not list-like

分析

在flask-sqlalchemy多对多的使用中构建关系方式出错
例:现有类Left 类Right两个类
class Left(db.Model):
    __tablename__ = 'left'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    left= db.relationship("Right", secondary=association_table ,backref="left")

    def __repr__(self):
        return ''.format(self.id)

class Right(db.Model):
    __tablename__ = 'right'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))

    def __repr__(self):
        return ''.format(self.id)
及关系表
association_table = db.Table('association',
                          db.Column('left_id', db.Integer, db.ForeignKey('left.id')),
                          db.Column('right_id', db.Integer, db.ForeignKey('right.id')))
在构建关系即给Left添加Right时未添加 [ ] 导致错误
        lleft = Left(name='老板')
        rright = Right(name='产品')
        db.session.add_all([lleft,rright])
        # 错误
        lleft.right = rright
        rright.left = lleft
        # 正确
        lleft.right = [rright]
        rright.left = [lleft]

解决

添加 [ ]

你可能感兴趣的:([已解决]Flask Incompatible collection type: 类名 is not list-like)