Sqlalchemy 数据库查询
Sqlalchemy Database Query
拜托,我需要有关如何在 sqlalchemy 中查询此类数据的帮助。我有一个这种格式的模型设计。
class Parent(db.model):
name = db.Column(db.String)
friends = db.Column(db.String)
account_status = db.Column(db.String, default='Inactive')
所以,我想查询:
my_friends = Parent.query.filter_by(friends=current_user.name).all()
这实际上给了我一个有我有他们的朋友的用户列表,但我也想只查询有我有他们的朋友但帐户状态为 'Active' 的用户并计算他们。
谢谢,欢迎并接受所有贡献。
已更新
filter()
可以采用多个条件。
my_friends = Parent.query.filter((Parent.friends==current_user.name) &
(Parent.account_status=="Active")).all()
此代码returns一个列表。如果要计算它们,请使用 len(my_friends)
.
@Muhteva 感谢您的帮助,您的回答为我提供了解决问题的方法。
当我尝试以与您相同的方式查询时 return 回溯错误:
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError:
name 'friends' is not defined
但是当我很好地研究你的代码时,我想出了这个对我有用的东西:
而不是像这样查询数据库:
my_friends = Parent.query.filter((friends==current_user.name) &
(account_status=="Active")).all()
我是这样查询的,包括模型 class 名称到列名称:
my_friends = Parent.query.filter((Parent.friends==current_user.name) &
(Parent.account_status=="Active")).all()
这对我有用。感谢@Muhteva 为我提供了如何实现这一目标的线索。
拜托,我需要有关如何在 sqlalchemy 中查询此类数据的帮助。我有一个这种格式的模型设计。
class Parent(db.model):
name = db.Column(db.String)
friends = db.Column(db.String)
account_status = db.Column(db.String, default='Inactive')
所以,我想查询:
my_friends = Parent.query.filter_by(friends=current_user.name).all()
这实际上给了我一个有我有他们的朋友的用户列表,但我也想只查询有我有他们的朋友但帐户状态为 'Active' 的用户并计算他们。
谢谢,欢迎并接受所有贡献。
已更新
filter()
可以采用多个条件。
my_friends = Parent.query.filter((Parent.friends==current_user.name) &
(Parent.account_status=="Active")).all()
此代码returns一个列表。如果要计算它们,请使用 len(my_friends)
.
@Muhteva 感谢您的帮助,您的回答为我提供了解决问题的方法。 当我尝试以与您相同的方式查询时 return 回溯错误:
Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError:
name 'friends' is not defined
但是当我很好地研究你的代码时,我想出了这个对我有用的东西: 而不是像这样查询数据库:
my_friends = Parent.query.filter((friends==current_user.name) &
(account_status=="Active")).all()
我是这样查询的,包括模型 class 名称到列名称:
my_friends = Parent.query.filter((Parent.friends==current_user.name) &
(Parent.account_status=="Active")).all()
这对我有用。感谢@Muhteva 为我提供了如何实现这一目标的线索。