在SQLAlchemy查询中使用for循环

6

我想在查询中使用for循环,如果记录的字段等于对象属性(在对象列表中)中的一个,则提取结果。 我该怎么做? 这是我的代码:

you = session.query(Users).filter_by(id=login_session['userid']).first()

friends = session.query(Friends).filter_by(user_id=login_session['userid']).all()

dashboard = session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()

但是我得到了这个:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
    response = self.full_dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1360, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1358, in full_dispatch_request
    rv = self.dispatch_request()
  File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1344, in dispatch_request
    return self.view_functions[rule.endpoint](**req.view_args)
  File "/home/pearadox6/travellr/app.py", line 423, in feed
    dashboard = session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()
  File "<string>", line 1, in <lambda>
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 51, in generate
    fn(self, *args[1:], **kw)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/query.py", line 1216, in filter
    criterion = expression._literal_as_text(criterion)
  File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/sql/expression.py", line 1521, in _literal_as_text
    "SQL expression object or string expected."
ArgumentError: SQL expression object or string expected.

为什么?
1个回答

8

为什么?

因为你不能将生成器对象作为filter的参数:

session.query(Markers).filter(Markers.owner == f.friend_id for f in friends).all()

使用列表和in_代替:
session.query(Markers).filter(Markers.owner.in_([f.friend_id for f in friends)]).all()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接