【问题标题】:Need to filter the existing queryset需要过滤现有的查询集
【发布时间】:2021-07-19 13:30:19
【问题描述】:

我需要在flask sqlalchemy 中进一步过滤现有的查询集。 例子 : 让Users表在数据库中有10000条记录... users=Users.query.filter(is_active=True)---得到1000条记录... 现在我只想使用这 1000 条记录,并想检查用户的位置是否为“Hyderabad”......而不是检查整个 10000 条记录,它应该只检查现有的 1000 条记录,以便提高性能。

我想我已经清楚地提到了问题陈述..

提前谢谢你...

【问题讨论】:

  • 这种方法应该没有必要。如果您在is_activelocation 上创建索引,RDBMS 应该会生成有效的查询。

标签: python sql postgresql flask sqlalchemy


【解决方案1】:

您可以像这样使用and__or 链接过滤器

类似的东西

from sqlalchemy import and_, or_, not_

query = meta.Session.query(User).filter(
    and_(
        User.is_active.like(search_variable_like),
        User.location.like(search_variable_location)
    )
)

更新 获取所有符合条件的用户记录

users = User.query.filter(is_active=True).all()

# now got the 1k records, check for location
hyderabad_users = []

for user in users:
   if user.location == 'Hyderabad':
      hyderabad_users.append(user)

【讨论】:

  • 但这将再次检查整个表数据。我想要的是,它应该只检查现有记录
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-09-17
  • 2010-12-26
  • 1970-01-01
  • 2021-05-30
  • 2020-08-22
  • 2019-04-15
相关资源
最近更新 更多