How to filter by multiple criteria in Flask SQLAlchemy?

35,277

Try this:

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

Timo

Updated on April 22, 2020

Comments

  • Timo
    Timo about 4 years

    I have a database shown below which works fine. Now I have a user called Bob that owns the space Mainspace. I would like to get a boolean to see if he is a owner of the space. I tried to apply two filters but I get the following error.

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

    Command:

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

    Database:

    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)