wbruntra
wbruntra

Reputation: 1061

Use the SQLAlchemy session in custom Flask-SQLAlchemy query method

I would like to create a custom method to tell me whether a row exists in my database. The SQLAlchemy exists method returns a subquery but doesn't execute anything, so I wanted to create the method does_exist, which will simply return True or False. Here is my code:

from flask_sqlalchemy import SQLAlchemy, BaseQuery, Model

class CustomBaseQuery(BaseQuery):
    def does_exist(self):
        return db.session.query(self.exists()).scalar()

db = SQLAlchemy(app, query_class=CustomBaseQuery)

This actually does work, but it seems wrong to refer to db.session within the body of the method, which thus depends on later naming the SQLAlchemy instance db. I would like to find a way to reference the eventual db.session object in a more general way.

Full working example here: https://gist.github.com/wbruntra/3db7b630e6ffb86fe792e4ed5a7a9578

Upvotes: 1

Views: 510

Answers (1)

Ilja Everilä
Ilja Everilä

Reputation: 52929

Though undocumented, the session used by the Query object is accessible as

self.session

so your more generic CustomBaseQuery could look like

class CustomBaseQuery(BaseQuery):
    def does_exist(self):
        return self.session.query(self.exists()).scalar()

Upvotes: 2

Related Questions