Recommand · October 22, 2021 0

Many-to-many relationships from multiple models using flask-sqlalchemy

For the Flask project which I am doing, I need to implement a feature that would enable multiple-authors for an article. However, the requirement is that the authors would come from two different classes (models) — that is,

  1. User
  2. Committee

These two models will have to be related with the third table, which is,

  1. Article

The models defined using flask-sqlalchemy as follows.

User model:

    class User(db.model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.UnicodeText)
        designation = db.Column(db.UnicodeText)

Committee model:

    class Committee(db.model):
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.UnicodeText)
        region = db.Column(db.UnicodeText)

Article model:

    class Article(db.model):
        id = db.Column(db.Integer, primary_key=True)
        title = db.Column(db.UnicodeText)
        body = db.Column(db.UnicodeText)
        authors = db.relationship()

I know the approach to implement a many-to-many relationship involving either Article-User or Article-Committee pairs. However, I am trying to implement Article-(User, Committee) relationships. That is, one article will have one or more user and/or committee as the author(s), and one user or one committee will have one or more articles. Is this possible at all?