简体   繁体   中英

Many to many query using flask_sqlalchemy

I got this models in a SQLAlchemy based app

class Task(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(512))
    status = db.Column(db.Enum(Status))


class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(512))
    user_tasks = db.relationship('Task',
                                 secondary=user_tasks, lazy='subquery',
                                 backref=db.backref('users', lazy=True)
                                )

user_tasks = db.Table('user_tasks',
    db.Column('task_id', db.Integer, db.ForeignKey('task.id'), primary_key=True),
    db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
    db.Column('value', db.Integer)
)

I want to join the 3 tables (using flask_sqlalchemy rather than a raw query) equivalent to:

db.session.execute(
                    'SELECT u.id, u.name, ut.value\
                     FROM user u\
                     JOIN user_tasks ut\
                     ON u.id = ut.user_id\
                     AND ut.task_id = :task_id\
                     JOIN task t\
                     ON t.id = ut.task_id',
                     {'task_id': task_id}
                   )

Thanks in advance

Below is a tested example.
Please note that due to the different ways these tables could be joined you will need to explicitly specify the joins, as in the example below, in order for SQLAlchemy to perform the query.

db.session.query(User.id,User.name,user_tasks.c.value).\ 
    join(user_tasks,user_tasks.c.user_id==User.id).\ 
    filter(user_tasks.task_id==task_id).\
    join(Task,Task.id==user_tasks.c.task_id).all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM