我正在尝试将 SQL 查询转换为 SQLAlchemy 查询以供用户在 get API 中使用。问题是我无法从关联表中查询任何内容。 (我确定我不知道该方法)。
ORM:
roles_users = db.Table(
'roles_users',
db.Column('user_id', db.Integer(), db.ForeignKey('user.id')),
db.Column('role_id', db.Integer(), db.ForeignKey('role.id'))
)
class Role(db.Model, RoleMixin):
id = db.Column(db.Integer(), primary_key=True)
name = db.Column(db.String(50), unique=True)
description = db.Column(db.String(255))
def __str__(self):
return self.name
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(50))
last_name = db.Column(db.String(50))
email = db.Column(db.String(50), unique=True)
password = db.Column(db.String(255))
.
.
.
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='dynamic'))
def __str__(self):
return self.email
工作 SQL 查询:
select first_name, last_name, role.name from user
join roles_users
join role on user.id = roles_users.user_id
and role.id = roles_users.role_id;
我遇到问题的 SQLAlchemy 查询:
roles_users.query.join(Role).join(User)
.filter(roles_users.user_id == User.id and
roles_users.role_id == Role.id).all()
我在使用上面的 SQLAlchemy 查询时出错:
AttributeError: 'Table' object has no attribute 'query'
如何使用 SQLAlchemy 执行与我的 SQL 查询等效的操作?
最佳答案
好的,所以在 Flask-Sql alchemy 中查询关联对象的关键是对 roles_users 进行外部连接。尝试先连接所有表,然后再过滤。我在下面发布答案。
query_user_role = User.query.join(roles_users).join(Role).
filter((roles_users.c.user_id == User.id) & (roles_users.c.role_id == Role.id)).all()
查询关联表对象时不要忘记加上'c'。没有它,它将无法工作。
还有一点,别忘了设置 backref lazy = 'joined'
关于python - 如何在 SQLAlchemy 中查询关联表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41270319/