Re: [sqlalchemy] Writing ORM from a complex sql statement

2019-06-11 Thread Simon King
Does something like this work? query = db.session.query(PostsModel).join(pn, PostsModel.id == pn.c.post_id).filter(pn.c.pn_nodes == db.session.query(n.c.n_nodes)) I can't help feeling this is a very inefficient query though. I still don't really understand your data model (I don't understand

Re: [sqlalchemy] Writing ORM from a complex sql statement

2019-06-10 Thread Desmond Lim
Okay, I have ORMed my sql statement: pn = db.session.query(PNModel.post_id, db.func.array_agg(PNModel.node_id.distinct()).label('pn_nodes')).group_by(PNModel.post_id) n = db.session.query(db.func.array_agg(NodesModel.id.distinct()).label('n_nodes')).filter(NodesModel.project_uuid ==

Re: [sqlalchemy] Writing ORM from a complex sql statement

2019-06-10 Thread Desmond Lim
Hi Simon, Sorry I think I really didn't make what I'm asking for clear. I have these codes nodes = NodesModel.find_by_project_uuid_and_topic_list(project_uuid=project_uuid, topic_list=node_dict['topics']) node_id_list = [node.id for node in nodes] select_sql = text('WITH pn_o AS (SELECT

Re: [sqlalchemy] Writing ORM from a complex sql statement

2019-06-10 Thread Simon King
I'm still not sure I understand. Here's an example that does what I *think* you're asking for: import sqlalchemy as sa import sqlalchemy.orm as saorm from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() pn = sa.Table( "pn", Base.metadata,

Re: [sqlalchemy] Writing ORM from a complex sql statement

2019-06-10 Thread Desmond Lim
Hi Simon, The tables and sample data are below. So first I search the nodes table for a and b, getting the node_id of them (in this example, 1 and 2). Then using the SQL statement, I would get all posts that have 1 and 2 as the node_id. So in the example data, 100, 103, 108 will be returned as

Re: [sqlalchemy] Writing ORM from a complex sql statement

2019-06-10 Thread Simon King
Hi Desmond. I don't really understand your table structure. Could you present it in the form of a standalone script that we can run (including sample data)? Thanks, Simon On Mon, Jun 10, 2019 at 2:57 AM Desmond Lim wrote: > > Hi there, > > I really have no idea how to do this via sqlalchemy.