简体   繁体   中英

Persistent where clause SQLAlchemy

I'm trying to add a persistent SQL where clause in SQLalchimy. Basically I have a table containing a specific field, and I want all my request to add a where clause, so this field matches a clause.

For instance, if my request is

session.query( MyTable ).all()

I'd like the generated request to be as such :

SELECT * FROM Table WHERE specific_field = 'some_value';

Is there a way of doing this without adding a filter to each request ?

Thanks in advance.

If you add:

dbengine.echo = True
session.query(MyTable).filter_by(specified_field = 'some_value').all()

I'm not sure what you mean by: 'without adding a filter to each request.' My guess is that you don't want to filter the request client-side. The generated SQL for this should look a lot like what you're asking for; the dbengine.echo = True bit will show you the SQL that's generated.

Update based on OP comment:

If you really want all queries to have a filter, then a simple (but in my opinion not so pretty) way would be to add your own query method:

def myquery(self, table):
  self.query(table).filter_by(specified_field = 'some_value')

session.__class__.some_arbitrarily_filtered_query = myquery

After that, you can just call (for example):

session.some_arbitrarily_filtered_query(MyTable).all()

I'm not really suggesting this as it's overly complicated, but...

CREATE VIEW Table2 AS SELECT * FROM Table WHERE specific_field = 'some_value';

then you reflect the view with

table2 = sqlalchemy.Table('Table2', metadata, autoload=True)

and just query there, possibly mapping it (also providing the primary key) to

class MyTable2(MyTable):
    pass

untested, but should work

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