Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is flask-sqlalchemy where in clause query syntax?

I`m using flask-sqlalchemy and my problem is where in clause like:

select * from table_1 where id in (1,2,3,5)
OR
select * from table_1 where field_1_id in (select id from table_2 where .... )

and get_or_create like peewee orm

Object.get_or_create(.......)

how can i generate this sentences with flask-sqlalchemy ?

like image 268
sdnaghdi Avatar asked Mar 15 '14 06:03

sdnaghdi


People also ask

How does the querying work with SQLAlchemy?

All SELECT statements generated by SQLAlchemy ORM are constructed by Query object. It provides a generative interface, hence successive calls return a new Query object, a copy of the former with additional criteria and options associated with it.

What is all () in SQLAlchemy?

method sqlalchemy.orm.Query. all() Return the results represented by this Query as a list. This results in an execution of the underlying SQL statement.

How do I SELECT in SQLAlchemy?

The select() method of table object enables us to construct SELECT expression. The resultant variable is an equivalent of cursor in DBAPI. We can now fetch records using fetchone() method. Here, we have to note that select object can also be obtained by select() function in sqlalchemy.

How do I SELECT a column in SQLAlchemy?

SQLAlchemy Core The already created students table is referred which contains 4 columns, namely, first_name, last_name, course, score. But we will be only selecting a specific column. In the example, we have referred to the first_name and last_name columns. Other columns can also be provided in the entities list.


2 Answers

Try .in_ clause in sqlalchemy

result = db_session.query(table_1).filter(table_1.id.in_((1,2,3,5))).all()

Note: here am assuming table_1 is your model

like image 142
kartheek Avatar answered Nov 15 '22 20:11

kartheek


Alternate you can also use the following syntax:

result = TableName.query.filter(TableName.id.in_([1,2,3]))

Note: I am using flask-sqlalchemy.

like image 36
Abdul Majeed Avatar answered Nov 15 '22 19:11

Abdul Majeed