Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter by multiple criteria in Flask SQLAlchemy?

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)
like image 303
Timo Avatar asked Sep 10 '17 14:09

Timo


1 Answers

Try this:

existing = User.query.join(User.spaces).filter(User.username=='Bob', Space.name=='Mainspace').first()
print(existing.id)
if existing != None:
  print('Exists')
like image 200
jz22 Avatar answered Sep 30 '22 12:09

jz22