Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help building an SQLAlchemy query + subquery

This is the SQL I need SQLAlchemy to generate via its ORM.

SELECT
    *
FROM
    notes
WHERE
    notes.student_id == {student_id} 
  OR
    notes.student_id IN (
        SELECT
            *
        FROM
            peers
        WHERE
            peers.student_id == {student_id}
          AND
            peers.date_peer_saved >= notes.date_note_saved
    )

The SQL is untested. I just wrote it to demo what I need SQLAlchemy to do.

Basically, the logged in student should see a list of saved notes. The only notes the student should see, however, are those posted by themself or those posted by one of their peers - But only those peers they 'friended' after the note had been saved.

This way, a student won't see notes posted by another student before they became peers.

I'm having trouble getting this to run in SQLAlchemy's ORM, however. Any help?

like image 670
dave Avatar asked Jun 13 '11 11:06

dave


People also ask

How do I create a SQLAlchemy query?

Python Flask and SQLAlchemy ORMAll 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 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.

Should I use SQLAlchemy core or ORM?

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. If you have a combination of needs that really could leverage both business objects and other data unrelated to the problem domain, use both!

Is it worth using SQLAlchemy?

SQLAlchemy is great because it provides a good connection / pooling infrastructure; a good Pythonic query building infrastructure; and then a good ORM infrastructure that is capable of complex queries and mappings (as well as some pretty stone-simple ones).


1 Answers

Basically, you can use the .subquery() method to get a sub query that you can place into another conditional like that.

Something like

subq = sess.query(Peers.id).filter(and_(Peers.student==student, XXX)).subquery()

Then

notes = sess.query(Notes).filter(or_(Notes.student==student, Notes.studing.in_(subq))).all()

(also untested and may not work with this actual query, but just to give you the idea).

like image 122
Keith Avatar answered Nov 10 '22 14:11

Keith