Murali
Murali

Reputation: 1114

Performing union with three queries - SQLAlchemy

In my project setup querying is being done based on the SQLAlchemy.

As per my previous requirements I have done the union with two queries.

Now I need to do Union with three queries.

Code is as follows:

query1 = query1.filter(model.name == "in-addr.arpa.")
query2 = query2.filter(model.tenant_id.in_(tenant_ids))
query = query1.union(query2)

Now Here I need to add one more query as follows:

query3 = query3.filter(model.tenant_id == context.tenant_id)

So I need to perform Union with all the three queries.

Upvotes: 13

Views: 11098

Answers (3)

Jonathan Biemond
Jonathan Biemond

Reputation: 548

In SQLAlchemy 1.4 you will need to use the function union and pass the queries as positional arguments instead of a list.

from sqlalchemy import union

query1 = query1.filter(model.name == "in-addr.arpa.")
query2 = query2.filter(model.tenant_id.in_(tenant_ids))
query3 = query3.filter(model.tenant_id == context.tenant_id)

query = union(query1, query2, query3)

Upvotes: 2

Ben
Ben

Reputation: 5208

This is how I did this in SQLAlchemy 1.3

from sqlalchemy import union

query1 = query1.filter(model.name == "in-addr.arpa.")
query2 = query2.filter(model.tenant_id.in_(tenant_ids))
query3 = query3.filter(model.tenant_id == context.tenant_id)

all_queries = [query1, query2, query3]
golden_set = union(*all_queries)

The change here is that the union method accepts a list of SQLAlchemy selectables.

Upvotes: 15

Murali
Murali

Reputation: 1114

The solution is following:

query1 = query1.filter(model.name == "in-addr.arpa.")
query2 = query2.filter(model.tenant_id.in_(tenant_ids))
query3 = query3.filter(model.tenant_id == context.tenant_id)
query = query1.union(query2,query3)

Upvotes: 14

Related Questions