Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a where exists in nested query with SQLAlchemy?

I'm trying to do a WHERE EXISTS clause in SQLAlchemy. The SQL looks like this:

SELECT
    id, title
FROM
    package AS package1
WHERE
    EXISTS (
        SELECT
            title
        FROM
            package as package2
        WHERE
            package1.id <> package2.id AND
            package1.title = package2.title
    )
ORDER BY
    title DESC;

Is it possible to do this in SQLAlchemy without using raw SQL? I've tried this but it doesn't seem to be returning the correct results:

    t = model.Session.query(
        model.Package.id,
        model.Package.title
    ).subquery('t')

    package = model.Session.query(
        model.Package.title
    ).filter(
        model.Package.id != t.c.id,
        model.Package.title == t.c.title
    )
like image 638
LondonAppDev Avatar asked Dec 07 '15 17:12

LondonAppDev


People also ask

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.

What does all () do in SQLAlchemy?

all() method. The Query object, when asked to return full entities, will deduplicate entries based on primary key, meaning if the same primary key value would appear in the results more than once, only one object of that primary key would be present. This does not apply to a query that is against individual columns.

What does SQLAlchemy all () return?

It does return an empty list.

What is SQLAlchemy aliased?

The alias in SQL corresponds to a “renamed” version of a table or SELECT statement, which occurs anytime you say “SELECT * FROM table1 AS a”. The AS creates a new name for the table. Aliases allow any table or subquery to be referenced by a unique name.


1 Answers

Use sqlalchemy.orm.aliased() and exists():

from sqlalchemy.orm import aliased

package_alias = aliased(Package)

session.query(Package.id, Package.title) \
       .filter(session.query(package_alias.title) \
                      .filter(Package.id != package_alias.id) \
                      .filter(Package.title == package_alias.title) \
                      .exists()) \
       .order_by(Package.title.desc())
like image 147
r-m-n Avatar answered Oct 11 '22 07:10

r-m-n