如何在烧瓶上使用sqlalchemy连接多个表

时间:2017-02-01 03:17:12

标签: python flask sqlalchemy many-to-many flask-sqlalchemy

我目前正在使用sqlalchemy工作烧瓶服务器。

我遇到了加入查询的问题。

我想获得与以下查询相同的结果,该结果将返回匹配用户加入的团队以及加入日期之后。

SELECT *
            FROM `match` as m
            join (
                SELECT  team_id,update_date
                FROM team_member
                where user_id = 108
            ) as mt
            on m.request_team_id = mt.team_id
            or m.against_team_id = mt.team_id
            WHERE mt.update_date <= timestamp(m.match_date,m.match_start_time)
            AND (m.match_status = 'PROGRESS' OR m.match_status= 'DONE')
            order by m.match_date desc

但是当我使用下面的子查询

Match.query.options(subqueryload(Match.team)).filter(TeamMember.user_id == user.user_id)\
            .filter(or_(Match.match_status == 'PROGRESS', Match.match_status == 'DONE')).\
            filter(TeamMember.update_date <= func.timestamp(Match.match_date, Match.match_start_time))\
            .order_by(Match.match_date.desc()).all()

当我打开查询调试和错误结果时,执行了两次查询。

我只想对此结果执行一个查询。

如何解决这个问题?

如果没有解决方案,我应该使用原始查询但是它不能绑定到模型吗?

这是我的模特。

class User(db.Model):
__tablename__ = 'user'
user_id = db.Column(db.INTEGER, primary_key=True)
email = db.Column(db.VARCHAR(200), unique=True)
team = db.relationship('Teams', secondary='team_member', primaryjoin=user_id == TeamMember.user_id)

class Teams(db.Model):
__tablename__ = 'teams'

team_id = db.Column(db.INTEGER, primary_key=True)
team_name = db.Column(db.VARCHAR(100),nullable=False, index=True)


class TeamMember(db.Model):
__tablename__ = 'team_member'
user_id = db.Column(db.Integer, db.ForeignKey('user.user_id'), primary_key=True)
team_id = db.Column(db.Integer, db.ForeignKey('teams.team_id'), primary_key=True)
role_name = db.Column(db.Enum("M","P"), default="P")
user = db.relationship('User', backref=backref("team_member", cascade="all, delete"))
team = db.relationship('Teams', backref=backref("team_member", cascade="all, delete"))
update_date = db.Column(db.DATETIME(), default=datetime.now())


class Match(db.Model):
__tablename__ = 'match'
match_id = db.Column(db.INTEGER, primary_key=True)
mc_id = db.Column(db.Integer)
request_team_id = db.Column(db.Integer, db.ForeignKey('teams.team_id'))
request_team_name = db.Column(db.VARCHAR(100))
against_team_id = db.Column(db.Integer, db.ForeignKey('teams.team_id'), nullable=True)
team = db.relationship('Teams', foreign_keys=[request_team_id, against_team_id], backref="matches", uselist=False,
                       primaryjoin="or_(Teams.team_id==Match.request_team_id, Teams.team_id==Match.against_team_id)")

0 个答案:

没有答案