简体   繁体   中英

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.

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)

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM