0

I have simple setup with SQLAlchemy currently it's setup to connect with existing database like this:

self.users = db.Table('users', self.metadata, autoload=True, autoload_with=self.engine)

It connects to existing table, but I don't know how to check for existing row when I connect to table when it's not created by SQLAlchemy.

What I've tried:

session.query(self.users.query.filter(self.users.id == 1).exists()).scalar()

I got that Table object doesn't have attribute query

2 Answers2

0

Your error means the Table object does not have a query attribute because SQLAlchemy has an separate Query API.

See this post How to query a table, in sqlalchemy

Musab Guma'a
  • 175
  • 2
  • 9
0

Alright for everybody wondering solution is following:

  1. Option

     check_existing = self.users.select().where(self.users.c.username == "admin")
     check_existing_result = session.execute(check_existing).fetchall()
    
     if len(check_existing_result) == 0:
         print('empty')
     else:
         print('found')
    
  2. Option

     query = session.query(self.users).all()
    
     for obj in query:
         if obj[1] == 'admin':
             print('true')
    
  3. Option

     check_existing = self.users.select().where(self.users.c.username == "admin")
     check_existing_result = session.execute(check_existing).scalar()
    
         if check_existing_result == None:
             print('empty')
         else:
             print('true')
    

Thanks to Executing a sqlalchemy exists query