-1

how can use custom query with flask-sqlalchemy ?

like:

db.custom_query("SELECT * FROM something WHERE id = ?", id).fetchall()

my query is something like this:

SELECT * FROM vacation WHERE vacation.id  in (SELECT * FROM users WHERE users.id == 5) 

and i dont know how can convert this to flask-sqlalchemy query

davidism
  • 121,510
  • 29
  • 395
  • 339
abcdefg
  • 9
  • 2
  • this may help [how-to-execute-raw-sql-in-flask-sqlalchemy-app](https://stackoverflow.com/questions/17972020/how-to-execute-raw-sql-in-flask-sqlalchemy-app) – sahasrara62 Feb 28 '23 at 10:40

1 Answers1

0

Using flask-sqlalchemy you can import your class table and use it to query. Given a User table you can do: all_users = User.query.all() this will return a list with all the users.

first_5_users = User.query.limit(5).all() this will return the first 5 users.

You can order, filter, and pretty much do anything. one_user = User.query.filter_by(id=1).first() This will return None if there is not user with id 1, or the user. last_5_confirmed_added_users = User.query.filter_by(confirmed=1).order_by(User.id.desc()).limit(5).all()

Hope this helps you.

Here are the query docs for flask-sqlalchemy.

LE: for your specific use case, if you have a VACATIONS and USERS table that have relationship where a user can have multiple vacations then to get all the vacations of a certain user you can do: user_vacations = Vacations.query.filter_by(user_id=2).all() this will return all the vacations of the user with id=2

Gl0deanR
  • 27
  • 8