Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use NOT IN clause in sqlalchemy ORM query

how do i convert the following mysql query to sqlalchemy?

SELECT * FROM `table_a` ta, `table_b` tb where 1 AND ta.id = tb.id AND ta.id not in (select id from `table_c`) 

so far i have this for sqlalchemy:

query = session.query(table_a, table_b) query = query.filter(table_a.id == table_b.id) 
like image 236
chrizonline Avatar asked Oct 03 '14 15:10

chrizonline


People also ask

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. The Query object, when asked to return either a sequence or iterator that consists of full ORM-mapped entities, will deduplicate entries based on primary key.

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 subquery in SQLAlchemy?

The grouping is done with the group_by() query method, which takes the column to use for the grouping as an argument, same as the GROUP BY counterpart in SQL. The statement ends by calling subquery() , which tells SQLAlchemy that our intention for this query is to use it inside a bigger query instead of on its own.

Should I use SQLAlchemy core or ORM?

If you want to view your data in a more schema-centric view (as used in SQL), use Core. If you have data for which business objects are not needed, use Core. If you view your data as business objects, use ORM. If you are building a quick prototype, use ORM.


2 Answers

The ORM internals describe the not_in() operator (previously notin_()), so you can say:

query = query.filter(table_a.id.not_in(subquery)) #                               ^^^^^^ 

From the docs:

inherited from the ColumnOperators.not_in() method of ColumnOperators

implement the NOT IN operator.

This is equivalent to using negation with ColumnOperators.in_(), i.e. ~x.in_(y).

Note that version 1.4 states:

The not_in() operator is renamed from notin_() in previous releases. The previous name remains available for backwards compatibility.

So you may find notin_() in some cases.

like image 141
fedorqui 'SO stop harming' Avatar answered Oct 12 '22 15:10

fedorqui 'SO stop harming'


Try this:

subquery = session.query(table_c.id) query = query.filter(~table_a.id.in_(subquery)) 

Note: table_a, table_b and table_c should be mapped classes, not Table instances.

like image 30
Slava Bacherikov Avatar answered Oct 12 '22 14:10

Slava Bacherikov