开发者

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 WHER开发者_JAVA技巧E 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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜