multi-helper table for many-many-many-… relationship in flask-sqlalchemy

狂风中的少年 提交于 2019-12-11 05:39:04

问题


Many questions were about many to many problem which could be solved with a helper table. But how about many-many-many... If there existed a more elegant way to handle this problem.

I tried to put an issue on https://github.com/pallets/flask-sqlalchemy/issues/710. But this guy reject to answer the question, or I think it's a feature instead of question.But anyway, he closed my issue.

Here is the minimal sample code, which I would like to handle the relationship among A,B,C in this way.

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')),
                     db.Column('id_c', db.Integer,
                               db.ForeignKey('c.id'))
                )

Here the models for A,B,C.


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')
    cs = db.relationship(
        'C', secondary=Helper_table, lazy='dynamic')

    def __repr__(self):
        return '<A {}>'.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')
    cs = db.relationship(
        'C', secondary=Helper_table, lazy='dynamic')

    def __repr__(self):
        return '<B {}>'.format(self.username)

class C(db.Model):  # C ORM
    id = db.Column(db.Integer, primary_key=True)

    def __repr__(self):
        return '<C {}>'.format(self.id)

Here is the Test code for them.

def test():
    s1 = A(username="a1_"+str(uuid.uuid4()))
    s2 = A(username="a2_"+str(uuid.uuid4()))
    t1 = B(username="b1_"+str(uuid.uuid4()))
    t2 = B(username="b2_"+str(uuid.uuid4()))

    c1 = C()
    c2 = C()
    c3 = C()
    c4 = C()



    t1.as.append(s1)
    t1.cs.append(c1)


    t1.as.append(s2)
    t1.cs.append(c2)

    t2.as.append(s1)
    t2.cs.append(c3)

    t2.as.append(s2)
    t2.cs.append(c4)

    db.session.add(t1)
    db.session.add(t2)
    db.session.commit()

At the first time the idea came into my mind. I thought maybe the code above could solve the problem. Unfortunately, after run these code, I found it didn't work as I wished.

Here is the helper table shows in the database. Not as I expected.

https://i.stack.imgur.com/A9i2F.png

Maybe my idea was totally wrong. I should use the old-school method to solve the problem.

来源:https://stackoverflow.com/questions/55553022/multi-helper-table-for-many-many-many-relationship-in-flask-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!