【问题标题】:How to filter by multiple criteria in Flask SQLAlchemy?如何在 Flask SQLAlchemy 中按多个条件进行过滤?
【发布时间】:2018-02-18 21:05:30
【问题描述】:

我有一个如下所示的数据库,它工作正常。现在我有一个名为 Bob 的用户,他拥有空间 Mainspace。我想得到一个布尔值,看看他是否是该空间的所有者。我尝试应用两个过滤器,但出现以下错误。

sqlalchemy.exc.InvalidRequestError: Can't compare a collection to an object or collection; use contains() to test for membership.

命令:

exists = Space.query.filter_by(name="Mainspace", owner="Bob").first()

数据库:

space_access = db.Table('space_access',
    db.Column('userid', db.Integer, db.ForeignKey('user.id')),
    db.Column('spaceid', db.Integer, db.ForeignKey('space.id')))

class User(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(15), unique=True)
    email = db.Column(db.String(50), unique=True)
    password = db.Column(db.String(80))
    role='admin';

    spaces = db.relationship('Space', secondary=space_access, backref=db.backref('owner', lazy='dynamic'))

class Space(UserMixin, db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50), unique=True)
    type = db.Column(db.String(50), unique=True)

【问题讨论】:

  • filter_by().first()。 First() 返回匹配或无。由于匹配项不为零,因此可以将其视为布尔值。
  • 我无法添加到过滤条件。请参阅我上面编辑过的帖子。
  • filter_by() 可以包含多个条件:filter_by(name='mainspace', owner='Bob').first()。 Flask 大量使用 SQLAlchemy。我建议您暂停并阅读 SQLAlchemy 文档和/或在线搜索一些教程。会让你受益匪浅
  • 我也试过了。没用。我想我必须加入一些东西,否则我的 backref 指向了错误的表。
  • 您的查询是否正确,但您在查询中缺少类名?来自the docssession.query(MyClass).filter_by(name = 'some name')。文档包括多条件过滤的情况。

标签: python mysql flask sqlalchemy flask-sqlalchemy


【解决方案1】:

试试这个:

existing = User.query.join(User.spaces).filter(User.username=='Bob', Space.name=='Mainspace').first()
print(existing.id)
if existing != None:
  print('Exists')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-15
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 2015-03-01
    • 2015-06-12
    • 2014-05-18
    • 2018-08-15
    相关资源
    最近更新 更多