What\'s the proper way to design a three-way many-to-many in flask-sqlalchemy?
Assume I have users, teams and roles. Users are assigned to teams. When assigned to a team
dudes. There is official way to solve the problem with two many-many by using a helper table.
Helper_table = db.Table('Helper_table',
db.Column('id_a', db.Integer,
db.ForeignKey('a.id')),
db.Column('id_b', db.Integer,
db.ForeignKey('b.id'))
)
class A(db.Model): # A ORM
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
bs = db.relationship(
'B', secondary=Helper_table, lazy='dynamic')
def __repr__(self):
return ''.format(self.username)
class B(db.Model): # B ORM
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
as = db.relationship(
'A', secondary=Helper_table, lazy='dynamic')
def __repr__(self):
return ''.format(self.username)
But it can only solve the two many-many problem !!! It will automatically handle the relationship.
a1 = A(username="a1_"+str(uuid.uuid4()))
b1 = B(username="b1_"+str(uuid.uuid4()))
a1.bs.append(b1)
db.session.add(a1)
db.session.commit()
As the code above shows that it will auto add b1
into database as well as b1.as
.
But when I tried this method in 3 many-many-many situation, everything f**k up.
Here are the questions I asked: multi-helper table for many-many-many-... relationship in flask-sqlalchemy
Generally, I think it should be a feature of this repo. There should be an elegant way to handle it.